美文网首页
面试题32(剑指offer)--从上到下打印二叉树

面试题32(剑指offer)--从上到下打印二叉树

作者: Tiramisu_b630 | 来源:发表于2019-08-17 19:16 被阅读0次

题目一:

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印 ,每一层打印一行

思路:

使用变量记录第几行有几个节点要打印,toBePrinted记录该行要打印的节点数量,nextLevel统计下一行要打印的节点数。

代码:

    /**
     * 分行从上到下打印
     * @param node
     */
    private static void Print(BinaryTreeNode node){
        if (node==null){
            return;
        }
        LinkedList<BinaryTreeNode> list=new LinkedList<>();
        list.offer(node);
        int nextLevel=0;
        int toBePrinted=1;
        while (!list.isEmpty()){
            BinaryTreeNode temp=list.poll();
            print(temp);
            if (temp.left!=null){
                list.offer(temp.left);
                nextLevel++;
            }
            if (temp.right!=null){
                list.offer(temp.right);
                nextLevel++;
            }
            toBePrinted--;
            if (toBePrinted==0){
                System.out.println();
                toBePrinted=nextLevel;
                nextLevel=0;
            }
        }
    }
    private static void print(BinaryTreeNode node){
        System.out.print(node.val+"\t");
    }

题目二:

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他以此类推。

思路:

用两个栈实现,一个栈先进左孩子,再进右孩子,另一个栈与之相反,一个栈存储一行的元素。

代码:

    /**
     * 之字形打印
     * @param node
     */
    private static void PrintCyc(BinaryTreeNode node){
        if (node==null){
            return;
        }
        Stack<BinaryTreeNode> stack1=new Stack<>();
        Stack<BinaryTreeNode> stack2=new Stack<>();
        stack1.push(node);
        while (!stack1.empty()||!stack2.empty()){
            if (stack2.empty()){
                while (!stack1.empty()){
                    BinaryTreeNode tmp=stack1.pop();
                    print(tmp);
                    if (tmp.left!=null){
                        stack2.push(tmp.left);
                    }
                    if (tmp.right!=null){
                        stack2.push(tmp.right);
                    }
                }
                System.out.println();
            }else {
                while (!stack2.empty()){
                    BinaryTreeNode tmp=stack2.pop();
                    print(tmp);
                    if (tmp.right!=null){
                        stack1.push(tmp.right);
                    }
                    if (tmp.left!=null){
                        stack1.push(tmp.left);
                    }
                }
                System.out.println();
            }
        }
    }
    private static void print(BinaryTreeNode node){
        System.out.print(node.val+"\t");
    }

相关文章

网友评论

      本文标题:面试题32(剑指offer)--从上到下打印二叉树

      本文链接:https://www.haomeiwen.com/subject/pfbksctx.html