Same Tree, Symmetric Tree, Balanced Binary Tree, Binary Tree Level Order Traversal, Binary Tree Level Order Traversal II, Maximum Depth of Binary Tree, Minimum Depth of Binary Tree
Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
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.
Recursive Solution
Two Nested Recursive:
getheight returns the highest depths of current node
break and return false if two children’s height differ by more than 1
else continue checking for both children, until reached null node.
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level). For example: Given binary tree {3,9,20,#,#,15,7},
1
2
3
4
5
3
/ \
9 20
/ \
15 7
return its level order traversal as:
1
2
3
4
5
[
[3],
[9,20],
[15,7]
]
BFS Solution
use two queues to store all nodes on the current level and their children level, when current level queue is empty, go to the next level
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
privatevoiddfs( ArrayList<ArrayList<Integer>> res, TreeNode root, int height){
if(root==null) return;
if(height>=res.size()){
res.add(new ArrayList<Integer>());
}
res.get(height).add(root.val);
dfs(res, root.left, height+1);
dfs(res, root.right, height+1);
}
Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree {3,9,20,#,#,15,7},
1
2
3
4
5
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
1
2
3
4
5
[
[15,7],
[9,20],
[3]
]
BFS Solution
Just reverse the result list at the end…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
privatevoiddfs( ArrayList<ArrayList<Integer>> res, TreeNode root, int height){
if(root==null) return;
if(height>=res.size()){
res.add(0,new ArrayList<Integer>());
}
res.get(res.size()-height-1).add(root.val);
dfs(res, root.left, height+1);
dfs(res, root.right, height+1);
}
Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
DFS Solution
A little different from max path: when one child is null, return the other half, when both is null return 1