Advertisement
sweet1cris

Untitled

Jan 9th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. //Recursive
  2. public ArrayList<Integer> postorderTraversal(TreeNode root) {
  3.     ArrayList<Integer> result = new ArrayList<Integer>();
  4.  
  5.     if (root == null) {
  6.         return result;
  7.     }
  8.  
  9.     result.addAll(postorderTraversal(root.left));
  10.     result.addAll(postorderTraversal(root.right));
  11.     result.add(root.val);
  12.  
  13.     return result;  
  14. }
  15.  
  16. //Iterative
  17. public ArrayList<Integer> postorderTraversal(TreeNode root) {
  18.     ArrayList<Integer> result = new ArrayList<Integer>();
  19.     Stack<TreeNode> stack = new Stack<TreeNode>();
  20.     TreeNode prev = null; // previously traversed node
  21.     TreeNode curr = root;
  22.  
  23.     if (root == null) {
  24.         return result;
  25.     }
  26.  
  27.     stack.push(root);
  28.     while (!stack.empty()) {
  29.         curr = stack.peek();
  30.         if (prev == null || prev.left == curr || prev.right == curr) { // traverse down the tree
  31.             if (curr.left != null) {
  32.                 stack.push(curr.left);
  33.             } else if (curr.right != null) {
  34.                 stack.push(curr.right);
  35.             }
  36.         } else if (curr.left == prev) { // traverse up the tree from the left
  37.             if (curr.right != null) {
  38.                 stack.push(curr.right);
  39.             }
  40.         } else { // traverse up the tree from the right
  41.             result.add(curr.val);
  42.             stack.pop();
  43.         }
  44.         prev = curr;
  45.     }
  46.  
  47.     return result;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement