Z-shaped Printed Binary Tree
subject
No, it's not on leetcode. I saw other people's interview questions and I looked for them on the bullock.
Please realize a function to print the two fork tree according to the zig zag pattern, that is, the first row is printed in the order from left to right, the second layer is printed in the right to left order, and the third line is printed in the order from left to right.
Solving problems
thinking
Define two stacks, the first time the stack is put into the left node and then the right node, so that the order is from right to left.
Put the data from the first stack into the second stack first from the right node to the left node, so that the order of output is from left to right.
Code
private static List<List<Integer>> zPrint(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) { return result; } Stack<TreeNode> stack1 = new Stack<>(); Stack<TreeNode> stack2 = new Stack<>(); stack1.push(root); /* Both stacks stopped only after they had no data. */ while (!stack1.empty() || !stack2.empty()) { List<Integer> row = new ArrayList<>(); while (!stack1.empty()) { TreeNode temp = stack1.pop(); row.add(temp.val); if (temp.left != null) { stack2.push(temp.left); } if (temp.right != null) { stack2.push(temp.right); } } if (row.size() != 0) { result.add(row); } row = new ArrayList<>(); while (!stack2.empty()) { TreeNode temp = stack2.pop(); row.add(temp.val); if (temp.right != null) { stack1.push(temp.right); } if (temp.left != null) { stack1.push(temp.left); } } if (row.size() != 0) { result.add(row); } } return result; }