首页 > 代码库 > Binary Tree Level Order Traversal leetcode java
Binary Tree Level Order Traversal leetcode java
题目:
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]]
题解:
这道题就是用传统的BFS来做。代码如下:
1 public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
3 if(root == null)
4 return res;
5
6 LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
7 queue.add(root);
8 int curLevCnt = 1;
9 int nextLevCnt = 0;
10 ArrayList<Integer> levelres = new ArrayList<Integer>();
11
12 while(!queue.isEmpty()){
13 TreeNode cur = queue.poll();
14 curLevCnt--;
15 levelres.add(cur.val);
16
17 if(cur.left != null){
18 queue.add(cur.left);
19 nextLevCnt++;
20 }
21 if(cur.right != null){
22 queue.add(cur.right);
23 nextLevCnt++;
24 }
25
26 if(curLevCnt == 0){
27 curLevCnt = nextLevCnt;
28 nextLevCnt = 0;
29 res.add(levelres);
30 levelres = new ArrayList<Integer>();
31 }
32 }
33 return res;
34 }
2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
3 if(root == null)
4 return res;
5
6 LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
7 queue.add(root);
8 int curLevCnt = 1;
9 int nextLevCnt = 0;
10 ArrayList<Integer> levelres = new ArrayList<Integer>();
11
12 while(!queue.isEmpty()){
13 TreeNode cur = queue.poll();
14 curLevCnt--;
15 levelres.add(cur.val);
16
17 if(cur.left != null){
18 queue.add(cur.left);
19 nextLevCnt++;
20 }
21 if(cur.right != null){
22 queue.add(cur.right);
23 nextLevCnt++;
24 }
25
26 if(curLevCnt == 0){
27 curLevCnt = nextLevCnt;
28 nextLevCnt = 0;
29 res.add(levelres);
30 levelres = new ArrayList<Integer>();
31 }
32 }
33 return res;
34 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。