LintCode | 69. 二叉树的层次遍历

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)


/**
 * 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> list = new ArrayList>();
        if(root != null) {
            ArrayList first = new ArrayList();
            list.add(first);
            first.add(root.val);
            //递归调用
            traverse(list, root.left, 1);
            traverse(list, root.right, 1);
        }
        return list;
    }

     /**
     * @param list: 通过参数传递来实现访问list
     * @param node: 欲遍历的结点
     * @param level: 当前结点的level(从0开始)
     */
    private void traverse(ArrayList> list, TreeNode node, int level) {
        ArrayList temp = null;
        //注意判空
        if(node != null) {
            //若list长度与当前结点所在level相同,说明该level尚未有对应ArrayList,则需创建
            //否则说明已创建,直接从list取出,并添加当前结点val
            if(list.size() == level) {
                temp = new ArrayList();
                list.add(temp);
            } else {
                temp = list.get(level);
            }
            temp.add(node.val);
            traverse(list, node.left, level + 1);
            traverse(list, node.right, level + 1);
        }
    }
}

你可能感兴趣的:(LintCode)