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来做。代码如下:
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 }
Binary Tree Level Order Traversal leetcode java,古老的榕树,5-wow.com
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。