首页 > 其他 > 详细

Binary Tree Level Order Traversal I,II

时间:2015-06-10 06:31:53      阅读:205      评论:0      收藏:0      [点我收藏+]

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]
]

 

ref http://www.cnblogs.com/springfor/p/3891391.html

知道用queue但是如何控制cur level和next level,ref给出了计数var, 标准的bfs做法

 

public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> res  = new ArrayList<ArrayList<Integer>>();
        if(root==null) return res;
        ArrayList<Integer> cl = new ArrayList<Integer>();
        LinkedList<TreeNode> q  = new LinkedList<TreeNode>();
        q.add(root);
        int curNum=1, nextNum=0;
        while(!q.isEmpty()){
            TreeNode n = q.poll();
            curNum--;
            cl.add(n.val);
            if(n.left!=null){
                q.add(n.left);
                nextNum++;
            }
            if(n.right!=null){
                q.add(n.right);
                nextNum++;
            }
            if(curNum==0){
                res.add(cl);
                cl = new ArrayList<Integer>();
                curNum  =nextNum;
                nextNum = 0;
            }
        }
        return res;
    }

Binary Tree Level Order Traversal II

res.add(0,cl); 

Binary Tree Level Order Traversal I,II

原文:http://www.cnblogs.com/jiajiaxingxing/p/4565045.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!