JZ60 --- 把二叉树打印成多行

题目描述:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

题解:
层序遍历

public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
    ArrayList<ArrayList<Integer>> res = new ArrayList<> ();
    Queue<TreeNode> queue = new LinkedList<> ();
    queue.offer (pRoot);
    while(!queue.isEmpty ()){
        ArrayList<Integer> list = new ArrayList<> ();
        int size = queue.size ();
        for(int i = 0;i < size;i++){
            TreeNode node = queue.poll ();
            if(node == null){
                continue;
            }
            list.add (node.val);
            queue.offer (node.left);
            queue.offer (node.right);
        }
        if(list.size () > 0){
            res.add (list);
        }
    }
    return res;
}

你可能感兴趣的:(剑指offer)