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++
- Traversals of binary tree
- Leetcode Binary Tree PathsLeetCode
- [LintCode] Binary Tree Level Order
- 545. Boundary of Binary Tree
- 257. Binary Tree Paths
- Construct String from Binary TreeStruct
- [LintCode] Check Full Binary Tree
- 257-Binary Tree Paths
- 543-Diameter of Binary Tree
- 563-Binary Tree Tilt
- 655-Print Binary Tree
- 654-Maximum Binary Tree
- 814-Binary Tree Pruning
- 110-Balanced Binary Tree
- 226-Invert Binary Tree
- 104. Maximum Depth of Binary Tree
- LeetCode 543. Diameter of Binary TreeLeetCode
- Binary Tree Level Order Traversal [LEETCODE]LeetCode
- LeetCode545.Boundary-of-Binary-TreeLeetCode
- Leetcode 226. Invert Binary TreeLeetCode
- [leetcode]binary-tree-inorder-traversalLeetCode
- [leetcode]maximum-depth-of-binary-treeLeetCode
- 662. Maximum Width of Binary Tree
- 173. Binary Search Tree Iterator
- [LeetCode] 226. Invert Binary TreeLeetCode
- [LeetCode] 543. Diameter of Binary TreeLeetCode
- LeetCode之Univalued Binary Tree(Kotlin)LeetCodeKotlin
- LeetCode之Binary Tree Pruning(Kotlin)LeetCodeKotlin
- 111-Minimum Depth of Binary Tree
- 662-Maximum Width of Binary Tree
- Binary-tree-level-order-traversal
- 104-Maximum Depth of Binary Tree
- 637-Average of Levels in Binary Tree
- 669-Trim a Binary Search Tree
- LeetCode 104. Maximum Depth of Binary TreeLeetCode
- LeetCode 98. Validate Binary Search TreeLeetCode
- LeetCode | 144. Binary Tree Preorder TraversalLeetCode