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]
]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
题意:给定二叉树。返回每层的节点值,从左到右。
分类:二叉树
解法1:层次遍历。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public List<List<Integer>> levelOrder(TreeNode root) {
- Stack<TreeNode> stack = new Stack<TreeNode>();
- List<List<Integer>> res = new ArrayList<List<Integer>>();
- if(root == null) return res;
- List<Integer> t = new ArrayList<Integer>();
- int low = 0;
- int high = 0;
- int ceng = 0;
- stack.add(root);
- t.add(root.val);
- res.add(t);
- t = new ArrayList<Integer>();;
- while(low<=high){
- TreeNode cur = stack.get(low);
- if(cur.left!=null){
- stack.add(cur.left);
- t.add(cur.left.val);
- high++;
- }
- if(cur.right!=null){
- stack.add(cur.right);
- t.add(cur.right.val);
- high++;
- }
- if(low==ceng){
- if(t.size()!=0) res.add(t);
- t = new ArrayList<Integer>();
- ceng = high;
- }
- low++;
- }
- return res;
- }
- }
解法2:思路和解法1一样,只是代码更加简洁。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public List<List<Integer>> levelOrder(TreeNode root) {
- ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
- LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
- LinkedList<Integer> curqueue = new LinkedList<Integer>();
- if(root==null) return res;
- int level = 1;
- queue.add(root);
- while(queue.size()>0){
- TreeNode cur = queue.poll();
- curqueue.add(cur.val);
- if(cur.left!=null){
- queue.add(cur.left);
- }
- if(cur.right!=null){
- queue.add(cur.right);
- }
- if(--level==0){
- ArrayList<Integer> arr = new ArrayList<Integer>(curqueue);
- res.add(arr);
- level = queue.size();
- curqueue.clear();
- }
- }
- return res;
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46378491