美文网首页
【剑指offer】之字形打印二叉树

【剑指offer】之字形打印二叉树

作者: 蛋花汤汤 | 来源:发表于2019-06-26 08:49 被阅读0次
    // 之字形打印二叉树
    public void printTree(TreeNode root){
        if(root == null)
            return ;

        Stack<TreeNode> odd = new Stack<TreeNode>(); // 存储奇数层节点
        Stack<TreeNode> even = new Stack<TreeNode>(); // 存储偶数层节点
        odd.push(root);

        while(!odd.isEmpty() || !even.isEmpty()){
            if(!odd.isEmpty()){
                while(!odd.isEmpty()){
                    TreeNode tmp = odd.pop();
                    System.out.printf(tmp.val + " ");
                    if(tmp.left != null)    even.push(tmp.left);
                    if(tmp.right != null)   even.push(tmp.right);
                }
            }else if(!even.isEmpty()){
                while(!even.isEmpty()){
                    TreeNode tmp = even.pop();
                    System.out.printf(tmp.val + " ");
                    if(tmp.right != null)   odd.push(tmp.right);
                    if(tmp.left != null)    odd.push(tmp.left);
                }
            }
            System.out.println();
        }
    }

相关文章

网友评论

      本文标题:【剑指offer】之字形打印二叉树

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