(Java refers to offer) Print the binary tree in zigzag order

1. Question analysis

Please implement a function to print the binary tree in a zigzag pattern, that is, the first line is printed from left to right, the second layer is printed from right to left, the third line is printed from left to right, and the other lines are printed from left to right. And so on.

This problem can be solved with the help of two stacks, one stack is used to store nodes in odd layers, and one stack is used to store nodes in even layers

Note that the odd-numbered layer is read from left to right, and the even-numbered layer is read from right to left, so the corresponding stack storage order is the opposite

Second, the code

public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
    
    
        //stack1 用来存储奇数层节点
        Stack<TreeNode> stack1 = new Stack<>();
        stack1.push(pRoot);
        //stack2 用来存储偶数层节点
        Stack<TreeNode> stack2 = new Stack<>();
        //用来记录层数
        int layer = 1;
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
        //当两个栈均非空时,出栈入栈
        while (!stack1.empty() || !stack2.empty()) {
    
    
            ArrayList<Integer> list = new ArrayList<>();
            //奇数层节点,将下一层节点存储到 stack2 中
            if (layer % 2 != 0) {
    
    
                while (!stack1.empty()) {
    
    
                    TreeNode pop = stack1.pop();
                    if (pop != null) {
    
    
                        list.add(pop.val);
                        stack2.push(pop.left);
                        stack2.push(pop.right);
                    }
                }
            } else {
    
    
                //偶数层节点,将下一层节点存储到 stack1 中
                while (!stack2.empty()) {
    
    
                    TreeNode pop = stack2.pop();
                    if (pop != null) {
    
    
                        list.add(pop.val);
                        stack1.push(pop.right);
                        stack1.push(pop.left);
                    }
                }
            }
            if (!list.isEmpty()) {
    
    
                lists.add(list);
                layer++;
            }
        }
        return lists;
    }

Three, summary

The key to this question is to use the first-in-last-out feature of the stack

Guess you like

Origin blog.csdn.net/nanhuaibeian/article/details/108773552