Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • Preorder
  • Inorder
  • Postorder
  • Stack -> Queue
  • E.X. isBinarySearchTree

Was this helpful?

6. Binary Tree

Preorder

Recursive

List<Integer> preorderTraversal(TreeNode root) {
  List<Integer> result = new ArrayList<>();
  preorder(root, result);
  return result;
}

private void preorder(TreeNode root, List<Integer> result){
    if (root == null){
        return;
    }
    result.add(root.val);
    preorder(root.left, result);
    preorder(root.right, result);
}

Divide & conquer

public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    if (root == null){
        return result;
    }

    List<Integer> left = preorderTraversal(root.left);
    List<Integer> right = preorderTraversal(root.right);

    result.add(root.val);
    result.addAll(left);
    result.addAll(right);

    return result;
}

Iterative

public List<Integer> preorderTraversal(TreeNode root) {
    Deque<TreeNode> queue = new LinkedList<>();
    List<Integer> result = new ArrayList<>();

    if(root == null){
        return result;
    }

    queue.push(root);

    while(!queue.isEmpty()){
        TreeNode node = queue.pop();
        result.add(node.val);
        if (node.right != null){
            queue.push(node.right);
        }
        if (node.left != null){
            queue.push(node.left);
        }
    }
    return result;
}

Morris

  • Save space but traverse the nodes twice

  • Time O(n)

def morrisInorder(root):
  def findPredecessor(node):
    pre = node.left
    while cur.right and cur.right != node:
      pre = pre.right
    return pre
  
  cur = root
  while cur:
    if cur.left:
      # find the rightest node in left subtree
      pre = findPredecessor(cur)
      # first traverse
      if not pre.right:
        pre.right = cur
        cur = cur.left
      # 2nd traverse
      else:
        pre.right = None
        print(cur.val)
        cur = cur.right
    else:
      print(cur.val)
      cur = cur.right

Inorder

  • Create TreeNode cur

  • 2 whiles, first put node to left bottom

Iterative

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    Deque<TreeNode> stack = new LinkedList<>();

    TreeNode cur = root;

    while(cur != null || !stack.isEmpty()){
        while(cur != null){
            stack.push(cur);
            cur = cur.left;
        }
        cur = stack.pop();
        result.add(cur.val);
        cur = cur.right;
    }
    return result;
}

O(1) Space

while node:
  while node.left and pre != node.left:
    node = node.left
    
  print(node.val)
  
  if node.right:
    node = node.right
  else:
    # 從right child leaf 退回
    while node.parent.right == node:
      node = node.partent
    # 從left child leaf 退回
    pre = node
    node = node.parent

Postorder

  • Create TreeNode pre & cur to compare

  • Push cur in stack

Iterative

public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    Deque<TreeNode> stack = new LinkedList<>();

    if (root == null){
        return result;
    }

    TreeNode pre = null;
    TreeNode cur = root;

    stack.push(cur);

    while(!stack.isEmpty()){
        cur = stack.peek();
        // traverse down
        if (pre == null || pre.right == cur || pre.left == cur){
            if (cur.left != null){        // has left child
                stack.push(cur.left);
            }else if (cur.right != null) {   // no left child
                stack.push(cur.right);
            }
        }else if (cur.left == pre){ // traverse up from left child
            if (cur.right != null){
                stack.push(cur.right);
            }
        }else{                      // traverse up form right child
            result.add(cur.val);
            stack.pop();
        }
        pre = cur;
    }
    return result;

Stack -> Queue

E.X. isBinarySearchTree

  • Create a class and put in queue

public static boolean isBST(BinaryTreeNode<Integer> tree){
  return inRange(tree, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

private static boolean inRange(BinaryTreeNode<Integer> tree, Integer lower, Integer upper){
  if (tree == null){
    return true;
  }

  if ( tree.data < lower || tree.data > upper){
    return false;
  }

  return inRange(tree.left, lower, tree.data) && inRange(tree.right, tree.data, upper);
}
private static class node{
  public BinaryTreeNode<Integer> nodeTree;
  public Integer lower, upper;

  public node(BinaryTreeNode<Integer> nodeTree, Integer lower, Integer upper){
    this.nodeTree = nodeTree;
    this.lower = lower;
    this.upper = upper;
    }
  }
public static boolean isBST(BinaryTreeNode<Integer> tree){
  Queue<node> q = new LinkedList<>();
  q.add(new node(tree, Integer.MIN_VALUE, Integer.MAX_VALUE));
  node head;
  while((head = q.poll()) != null){
    if (head.nodeTree == null){
        return true;
    }
    if ( head.nodeTree.data < head.lower || head.nodeTree.data > head.upper){
        return false;
    }

    q.add(new node(head.nodeTree.left, head.lower, head.nodeTree.data));
    q.add(new node(head.nodeTree.right, head.nodeTree.data, head.upper));
  }
  return true;
}
PreviousSplit Array Largest SumNextGeneral

Last updated 4 years ago

Was this helpful?