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

    // 之字形打印二叉树
    public void printTree(TreeNode root){
        if(root == null)
            return ;

        Stack odd = new Stack(); // 存储奇数层节点
        Stack even = new Stack(); // 存储偶数层节点
        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】之字形打印二叉树)