Tuesday, July 29, 2014

[LeetCode] 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? 

解题思路: BSF,一层一层的打印

Java Code

public List> levelOrder(TreeNode root) {
        List> res = new ArrayList>();
        Queue tmp = new LinkedList();
        
        if(root == null) return res;
        
        tmp.add(root);
        while(!tmp.isEmpty()){
            int size = tmp.size();
            List level = new ArrayList();
            
            for(int i = 0; i < size; i++){
                TreeNode node = tmp.poll();
                level.add(node.val);
                if(node.left != null) tmp.add(node.left);
                if(node.right != null) tmp.add(node.right);
            }
            
            res.add(level);
        }
        
        return res;
    }

No comments:

Post a Comment