首页 > 代码库 > 32: Binary Tree Level Order Traversal

32: Binary Tree Level Order Traversal

    /************************************************************************/
        /*       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