-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay-2 Binary Tree Level Order Traversal II
70 lines (60 loc) · 1.77 KB
/
Day-2 Binary Tree Level Order Traversal II
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result=new ArrayList<>();
if(root==null) return result;
Queue<TreeNode> st=new LinkedList<>();
st.add(root);
int count=1;
while(!st.isEmpty()){
List<Integer> l=new ArrayList<>();
int num=0;
while(count-->0){
TreeNode t=st.remove();
if(t.left!=null){
st.add(t.left);
num++;
}
if(t.right!=null){
st.add(t.right);
num++;
}
l.add(t.val);
}
count=num;
result.add(0,l);
}
return result;
}
}
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result=new ArrayList<>();
if(root==null) return result;
dfs(root,0,result);
return result;
}
void dfs(TreeNode root, int depth,List<List<Integer>> result){
if(root==null) return;
if(result.size()==depth){
result.add(0,new ArrayList<>());
}
result.get(result.size()-depth-1).add(root.val);
dfs(root.left,depth+1,result);
dfs(root.right,depth+1,result);
}
}