Tree

Tree

1. Traversal

(1) Preorder Traversal

    // Iterative version
    public List<Integer> preorderTraversal(TreeNode root) {
       List<Integer> res = new ArrayList<>();

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

       Stack<TreeNode> stack = new Stack<>();
       stack.push(root);

       while (!stack.isEmpty()) {
           TreeNode curNode = stack.pop();
           res.add(curNode.val);

           if (curNode.right != null) {
               stack.push(curNode.right);
           }

           if (curNode.left != null) {
               stack.push(curNode.left);
           } 
       }
       return res;
    }

(2) Inorder Traversal

(3) Postorder Traversal

2. DFS and BFS in Tree

(1) BFS

This is essentially Binary Tree Level Order Traversalarrow-up-right

(2) DFS

3. Binary Search Tree

  1. Check if a tree is binary search tree: Validate Binary Search Treearrow-up-right

  2. Based on the property of Binary Search Tree, we can implement Binary Search to retrieve a value: Kth Smallest Element in a BSTarrow-up-right

4.Threaded Tree (Morris Tree)

Threaded Tree can guarantee O(n) time in traversal and O(1) space

(1) Preorder Traversal

(2) Inorder Traversal

(3) Postorder Traversal

5. Question Category

Last updated