`

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

二叉树的广度优先搜索,用队列来实现,借助两个变量来记录每一层的节点个数,以及何时将每层的节点的值加入到结果集中。代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if(root == null) return result;
        int count = 0;
        int helper = 1;
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode node = queue.poll();
            list.add(node.val);
            helper --;
            if(node.left != null) {
                queue.offer(node.left);
                count ++;
            }
            if(node.right != null) {
                queue.offer(node.right);
                count ++;
            }
            if(helper == 0) {
                result.add(new ArrayList<Integer>(list));
                helper = count;
                count = 0;
                list.clear();
            }
        }
        return result;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics