LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)
LeetCode#110.Balanced Binary Tree_Tree/Height/DFS/Recursion
題目
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 left and right subtrees of every node differ in height by no more than 1.
要點
基本概念
root ---> leaves
*Level*
start from 1 ---> += 1
*Depth*
start from 0 ---> += 1
or = Level -1
*Height*
start from max(depth) ---> -= 1
參考資料
解題
解法一
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
“””
def check(root):
if not root: return 0
left = check(root.left)
right = check(root.right)
if left == -1 or right == -1 or abs(left-right) > 1:
return -1
return 1 + max(left, right)
return check(root) != -1
解法二
class Solution(object):
def height(self, root):
if not root: return -1
return 1 + max(self.height(root.left), self.height(root.right))
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: return True
return abs(self.height(root.left) - self.height(root.right)) < 2 \
and self.isBalanced(root.left) \
and self.isBalanced(root.right)
相關文章
- LeetCode C++ 968. Binary Tree Cameras【Tree/DFS】困難LeetCodeC++
- 【DFS】HDU 5423 Rikka with Tree
- Leetcode Binary Tree PathsLeetCode
- 173. Binary Search Tree Iterator
- LeetCode Invert Binary TreeLeetCode
- Leetcode Balanced Binary TreeLeetCode
- Construct String from Binary TreeStruct
- [LintCode] Binary Tree Level Order
- [LintCode] Check Full Binary Tree
- LeetCode-Binary Tree PathsLeetCode
- leetcode - Binary Tree Preorder TraversalLeetCode
- Leetcode Binary Tree Inorder TraversalLeetCode
- Leetcode Binary Tree Preorder TraversalLeetCode
- Leetcode Binary Tree Postorder TraversalLeetCode
- Leetcode Maximum Depth of Binary TreeLeetCode
- Leetcode-Balanced Binary TreeLeetCode
- Balanced Binary Tree leetcode javaLeetCodeJava
- Codefroces 1328E Tree Querie(dfs序)
- LeetCode545.Boundary-of-Binary-TreeLeetCode
- Binary Tree Level Order Traversal [LEETCODE]LeetCode
- [leetcode]maximum-depth-of-binary-treeLeetCode
- [leetcode]binary-tree-inorder-traversalLeetCode
- [LeetCode] 543. Diameter of Binary TreeLeetCode
- LeetCode 543. Diameter of Binary TreeLeetCode
- LeetCode-Serialize and Deserialize Binary TreeLeetCode
- 501-Find Mode in Binary Search Tree
- Construct Binary Tree from Preorder and Inorder TraversalStruct
- LintCode-Serialization and Deserialization Of Binary Tree
- Leetcode Binary Tree Level Order TraversalLeetCode
- Leetcode Validate Binary Search TreeLeetCode
- Leetcode Minimum Depth of Binary TreeLeetCode
- Leetcode Binary Tree Maximum Path SumLeetCode
- Interview-Largest independent set in binary tree.View
- Leetcode-Binary Tree Postorder TraversalLeetCode
- Leetcode-Binary Tree Inorder TraversalLeetCode
- Leetcode-Maximum Depth of Binary TreeLeetCode
- Construct Binary Tree from Inorder and Postorder TraversalStruct
- leetcode 之 Recover Binary Search TreeLeetCode