leetcode 110. Balanced Binary Tree
Posted 将者,智、信、仁、勇、严也。
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 110. Balanced Binary Tree相关的知识,希望对你有一定的参考价值。
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3 / 9 20 / 15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1 / 2 2 / 3 3 / 4 4
Return false.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def helper(node): if not node: return True, 0 l_b, l_h = helper(node.left) r_b, r_h = helper(node.right) if not l_b or not r_b or abs(l_h-r_h) > 1: return False, max(l_h, r_h)+1 return True, max(l_h, r_h)+1 ans, _ = helper(root) return ans
或者是直接在获取tree高度的时候用一个成员变量来记录是否平衡。
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ self.ans = True def get_depth(node): if not node: return 0 l, r = get_depth(node.left), get_depth(node.right) if abs(l-r) > 1: self.ans = False return max(l, r)+1 get_depth(root) return self.ans
另外的解法就是使用高度是否为-1来标识是否平衡。
class solution { public: int dfsHeight (TreeNode *root) { if (root == NULL) return 0; int leftHeight = dfsHeight (root -> left); if (leftHeight == -1) return -1; int rightHeight = dfsHeight (root -> right); if (rightHeight == -1) return -1; if (abs(leftHeight - rightHeight) > 1) return -1; return max (leftHeight, rightHeight) + 1; } bool isBalanced(TreeNode *root) { return dfsHeight (root) != -1; } };
最笨的方法就是N^2复杂度的:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {boolean} def isBalanced(self, root): if not root: return True return abs(self.getHeight(root.left) - self.getHeight(root.right)) < 2 and self.isBalanced(root.left) and self.isBalanced(root.right) def getHeight(self, root): if not root: return 0 return 1 + max(self.getHeight(root.left), self.getHeight(root.right))
以上是关于leetcode 110. Balanced Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 110. Balanced Binary Tree 递归求解
[LeetCode]题解(python):110 Balanced Binary Tree
leetcode-110. Balanced Binary Tree
LeetCode_110. Balanced Binary Tree