目录
Tree: Height/Depth/Level
Height
Height of node:
- The height of a node is the number of edges on the longest downward path between that node and a leaf.
Height of tree:
- The height of a tree is the number of edges on the longest downward path between the root and a leaf.
- The height of a tree is the height of its root.
- Height starts from max(depth)
- The height of None is -1
- The height of a root(w/o any leaf node) is 0.
- The height of a root(w/ at least one leaf node) is 1.
- The height of an inner node is 1 + max(height(node.left), height(node.right)).
- The height of a leaf(w/o any child node) is 0.
110.Balanced Binary Tree
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.
def height(self, root):
if not root: return -1
return 1 + max(self.height(root.left), self.height(root.right))
def isBalanced(self, root):
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)
Depth
Depth:
- The depth of a node is the number of edges from the node to the tree’s root node.
- Depth starts from 1
- The depth of None is -1
- The depth of a root is 0.
104. Maximum Depth of Binary Tree
104. Maximum Depth of Binary Tree.
A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
def maxDepth(self, root):
if not root: return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
111. Minimum Depth of Binary Tree
111. Minimum Depth of Binary Tree.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
def minDepth(self, root):
if not root: return 0
children = [root.left, root.right]
# if we're at leaf node
if not any(children): return 1
min_depth = float('inf')
for c in children:
if c:
# here we do not plus 1
min_depth = min(self.minDepth(c), min_depth)
return min_depth + 1
Level
Level:
- The level of a node is defined by 1 + the number of connections between the node and the root.
- Level = Depth + 1
- Level starts from 1
- The level of None is 0
- The level of the root is 1
102. Binary Tree Level Order Traversal
102. Binary Tree Level Order Traversal
def levelOrder(self, root):
levels = []
if not root: return levels
def helper(node, level):
# start the current level
if len(levels) == level:
levels.append([]
# append the current node value
levels[level].append(node.val)
# process child nodes for the next level
if node.left:
helper(node.left, level + 1)
if node.right:
helper(node.right, level + 1)
helper(root, 0)
return levels