-
Notifications
You must be signed in to change notification settings - Fork 171
/
BinaryTreeLevelOrderTraversal.java
executable file
·76 lines (71 loc) · 2.13 KB
/
BinaryTreeLevelOrderTraversal.java
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
71
72
73
74
75
76
/*
Author: Andy, [email protected]
Date: Dec 12, 2014
Problem: Binary Tree Level Order Traversal
Difficulty: easy
Source: https://oj.leetcode.com/problems/binary-tree-level-order-traversal/
Notes:
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},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Solution: 1. Use queue. In order to seperate the levels, use 'NULL' as the end indicator of one level.
2. DFS.
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder_1(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
q.offer(null);
List<Integer> level = new ArrayList<Integer>();
while(true) {
TreeNode node = q.poll();
if (node != null) {
level.add(node.val);
if(node.left!=null) q.offer(node.left);
if(node.right!=null) q.offer(node.right);
} else {
res.add(level);
level = new ArrayList<Integer>();
if(q.isEmpty()==true) break;
q.offer(null);
}
}
return res;
}
public List<List<Integer>> levelOrder_2(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) return res;
levelOrderRe(root, 0, res);
return res;
}
public void levelOrderRe(TreeNode root, int level, List<List<Integer>> res) {
if(root == null) return;
if(level == res.size()) res.add(new ArrayList<Integer>());
res.get(level).add(root.val);
levelOrderRe(root.left, level+1, res);
levelOrderRe(root.right,level+1, res);
}
}