二叉树的层次遍历,lintcode

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
给一棵二叉树 {3,9,20,#,#,15,7} :
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]

解题思路:用一个队列实现,队列保存每层的节点,以此遍历每层。
一刷ac

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Level order a list of lists of integer
     */
    public ArrayList> levelOrder(TreeNode root) {
        ArrayList> rst = new ArrayList>();
        if(root == null) return rst;
        LinkedList list = new LinkedList();
        list.offer(root);
        while(!list.isEmpty()){
            ArrayList res = new ArrayList();
            int size = list.size();
            for(int i = 0; i < size; i++){
                TreeNode node = list.poll();
                if(node.left != null) list.offer(node.left);
                if(node.right != null) list.offer(node.right);
                res.add(node.val);
            }
            rst.add(res);
        }
        return rst;
    }
}

你可能感兴趣的:(lintcode)