首页 > 其他 > 详细

32: Binary Tree Level Order Traversal

时间:2015-01-27 23:05:02      阅读:248      评论:0      收藏:0      [点我收藏+]

    /************************************************************************/
        /*       32:      Binary Tree Level Order Traversal                                          */
        /************************************************************************/
        /*
         * 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.
         * */
        
        //从根节点到叶子节点分层遍历树

 

public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            List<TreeNode> level = new ArrayList<>();
            level.add(root);
            while(true){
                if (level.isEmpty() || level.get(0) == null){
                    break;
                }
                List<TreeNode> nextLevel = new ArrayList<>();
                List<Integer> currentLevel = new ArrayList<>();

                for (TreeNode node : level){
                    currentLevel.add(node.val);
                    if (node.left != null) nextLevel.add(node.left);
                    if (node.right != null) nextLevel.add(node.right);
                }
                result.add(currentLevel);
                level = nextLevel;
            }
            return result;
            }

 

32: Binary Tree Level Order Traversal

原文:http://www.cnblogs.com/theonemars/p/4254101.html

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