|
| 1 | +/* package whatever; // don't place package name! */ |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.lang.*; |
| 5 | +import java.io.*; |
| 6 | + |
| 7 | +/* Name of the class has to be "Main" only if the class is public. */ |
| 8 | +class Ideone |
| 9 | +{ |
| 10 | + static class TreeNode { |
| 11 | + int val; |
| 12 | + TreeNode left = null, right = null; |
| 13 | + TreeNode(int value) {this.val = value;} |
| 14 | + } |
| 15 | + public static void main (String[] args) throws java.lang.Exception |
| 16 | + { |
| 17 | + TreeNode root = new TreeNode(0); |
| 18 | + root.left = new TreeNode(2); |
| 19 | + root.right = new TreeNode(3); |
| 20 | + root.left.left = new TreeNode(4); |
| 21 | + root.left.right = new TreeNode(5); |
| 22 | + while (root != null) { |
| 23 | + // more preferred way to create a stack |
| 24 | + Deque<Integer> stack = new ArrayDeque<Integer>(); |
| 25 | + helper(root, root.left, stack); |
| 26 | + helper(root, root.right, stack); |
| 27 | + if (stack.isEmpty()) { |
| 28 | + stack.addFirst(root.val); |
| 29 | + System.out.println(Arrays.toString(stack.toArray())); |
| 30 | + root = null; |
| 31 | + } else { |
| 32 | + System.out.println(Arrays.toString(stack.toArray())); |
| 33 | + } |
| 34 | + |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public static void helper(TreeNode rootOfRoot,TreeNode root, Deque<Integer> stack) { |
| 39 | + if (root == null) return; |
| 40 | + else if (root.left == null && root.right == null) { |
| 41 | + System.out.println("root.val= " + root.val); |
| 42 | + stack.addFirst(root.val); |
| 43 | + if (root == rootOfRoot.left) rootOfRoot.left = null; |
| 44 | + else rootOfRoot.right = null; |
| 45 | + return; |
| 46 | + } else { |
| 47 | + helper(root, root.left, stack); |
| 48 | + helper(root, root.right, stack); |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments