My Algorithm Summary
  • Introduction
  • Data Structure
    • Linked List
    • Stack
      • Monotone Stack
        • 42 Trapping Rain Water
        • 84 Largest Rectangle in Histogram
        • 85 Maximal Rectangle
        • 255 Verify Preorder Sequence in Binary Search Tree
        • 316 Remove Duplicate Characters
        • 402 Remove K Digits
        • 456 132 Pattern
        • 496 Next Greater Element I
        • 503 Next Greater Element II
      • 20 Valid Parentheses
      • 71 Simplify Path
      • 150 Evaluate Reverse Polish Notation
      • 155 Min Stack
      • 173 Binary Search Tree Iterator
      • 224 Basic Calculator
      • 227 Basic Calculator II
      • 232 Implement Queue using Stacks
      • 341 Flatten Nested List Iterator
      • 394 Decode String
      • 439 Ternary Expression Parser
      • 636 Exclusive Time of Functions
    • Heap
    • Trie
    • Segment Tree
    • Tree
      • 94 Binary Tree Inorder Traversal
      • 104 Maximum Depth of Binary Tree
      • 144 Binary Tree Preorder Traversal
      • 145 Binary Tree Postorder Traversal
      • 199 Binary Tree Right Side View
      • 226 Invert Binary Tree
      • 272 Closest Binary Search Tree Value II
      • 508 Most Frequent Subtree Sum
      • 513 Find Bottom Left Tree Value
      • 515 Find Largest Value in Each Tree Row
      • 617 Merge Two Binary Trees
      • 637 Average of Levels in Binary Tree
      • 653 Two Sum IV - Input is a BST
      • 654 Maximum Binary Tree
      • 669 Trim a Binary Search Tree
      • 666 Path Sum IV
      • 230 Kth Smallest Element in a BST
      • 250 Count Univalue Subtrees
      • 538 Convert BST to Greater Tree
      • 404 Sum of Left Leaves
      • 582 Kill Process
      • 112 Path Sum
      • 108 Convert Sorted Array to Binary Search Tree
      • 111 Minimum Depth of Binary Tree
      • 501 Find Mode in Binary Search Tree
      • 102 Binary Tree Level Order Traversal
      • 107 Binary Tree Level Order Traversal II
      • 103 Binary Tree Zigzag Level Order Traversal
      • 113 Path Sum II
      • 437 Path Sum III
      • 99 Recover Binary Search Tree
      • 687 Longest Univalue Path
      • 285 Inorder Successor in BST
      • 101 Symmetric Tree
      • 129 Sum Root to Leaf Numbers
      • 298 Binary Tree Longest Consecutive Sequence
      • 270 Closest Binary Search Tree Value
      • 549 Binary Tree Longest Consecutive Sequence II
      • 98 Validate Binary Search Tree
      • 652 Find Duplicate Subtrees
      • 314 Binary Tree Vertical Order Traversal
      • 333 Largest BST Subtree
      • 563 Binary Tree Tilt
      • 110 Balanced Binary Tree
    • Graph
      • Detect Cycle
  • Algorithms
    • Union Find
      • 695 Max Area of Island
      • 684 Redundant Connection
    • Binary Search
    • Topological Sorting
    • Breadth-First Search
      • 694 Number of Distinct Islands
    • Depth-First Search
    • Two Pointers
    • Sorting
    • Backtacking
    • Dynamic Programming
      • Interval DP
        • Matrix Chain Multiplication
        • Merge Stone
      • KnapSack Problem
        • 0-1 KnapSack
        • Unbounded KnapSack
      • Longest Increasing Subsequence
      • Longest Common Subsequence
    • Reservior Sampling
    • Bipartite Graph
      • Check Bipartite Graph
      • Maximal Matching - Hungarian Algorithm
    • String Pattern Matching
      • KMP Algorithm
      • Rabin Karp Algorithm
  • System Design
    • Consistent Hashing
    • Bloom Filter
    • Caching
      • LRU
      • LFU
    • Mini Twitter
    • Tiny Url
Powered by GitBook
On this page
  • Tree
  • 1. Traversal
  • (1) Preorder Traversal
  • (2) Inorder Traversal
  • (3) Postorder Traversal
  • 2. DFS and BFS in Tree
  • (1) BFS
  • (2) DFS
  • 3. Binary Search Tree
  • 4.Threaded Tree (Morris Tree)
  • (1) Preorder Traversal
  • (2) Inorder Traversal
  • (3) Postorder Traversal
  • 5. Question Category

Was this helpful?

  1. Data Structure

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

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

        Stack<TreeNode> stack = new Stack<>();
        while (curNode != null || !stack.isEmpty()) {
            if (curNode != null) {
                stack.push(curNode);
                curNode = curNode.left;
            }
            else {
                curNode = stack.pop();
                res.add(curNode.val);
                curNode = curNode.right;
            }
        }
        return res;
    }

(3) Postorder Traversal

    // Iterative version
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode curNode = null, preNode = null;

        while (!stack.isEmpty()) {
            curNode = stack.peek();
            // Case 1: Traverse down the tree, put left child into stack if it exists, otherwise put right child
            if (preNode == null || preNode.left == curNode || preNode.right == curNode) {
                if (curNode.left != null) {
                    stack.push(curNode.left);
                }
                else if (curNode.right != null) {
                    stack.push(curNode.right);
                }
            }
            // Case 2: Travese up from left child
            else if (curNode.left == preNode) {
                if (curNode.right != null) {
                    stack.push(curNode.right);
                }
            }
            // Case 3: Traverse up from right child
            else {
                res.add(curNode.val);
                stack.pop();
            }
            preNode = curNode;
        }
        return res;
    }

2. DFS and BFS in Tree

(1) BFS

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();

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

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        List<Integer> level = null;

        while (!queue.isEmpty()) {
            int size = queue.size();
            level = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();

                level.add(curNode.val);

                if (curNode.left != null) {
                    queue.add(curNode.left);
                }

                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
            res.add(level);
        }
        return res;
    }

(2) DFS

    public int getTreeSize(TreeNode node) {
        if (node == null) {
            return 0;
        }

        int leftSize = getTreeSize(node.left);
        int rightSize = getTreeSize(node.right);

        return 1 + leftSize + rightSize;
    }
    public int getTreeHeight(TreeNode node) {
        if (node == null) {
            return 0;
        }

        int leftHeight = getTreeHeight(node.left);
        int rightHeight = getTreeHeight(node.right);

        return Math.max(leftHeight, rightHeight) + 1;
    }

3. Binary Search Tree

4.Threaded Tree (Morris Tree)

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

(1) Preorder Traversal

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

       TreeNode curNode = root;
       TreeNode preNode = null;

       while (curNode != null) {
           if (curNode.left == null) {
               res.add(curNode.val);
               curNode = curNode.right;
           }
           else {
               preNode = curNode.left;
               // Get the predecessor of curNode
               while (preNode.right != null && preNode.right != curNode) {
                   preNode = preNode.right;
               }

               // Case 1: Find the predecessor of curNode, traversing down
               if (preNode.right == null) {
                   res.add(curNode.val);
                   preNode.right = curNode;
                   curNode = curNode.left;
               }
               // Case 2: Disconnect with predecessor, traversing up
               else {
                   preNode.right = null;
                   curNode = curNode.right;
               }
           }
       }
       return res;
    }

(2) Inorder Traversal

TreeNode preNode = null;
        TreeNode curNode = root;

        while (curNode != null) {
            if (curNode.left == null) {
                res.add(curNode.val);
                curNode = curNode.right;
            }
            else {
                preNode = curNode.left;
                while (preNode.right != null && preNode.right != curNode) {
                    preNode = preNode.right;
                }

                if (preNode.right == null) {
                    preNode.right = curNode;
                    curNode = curNode.left;
                }
                else {
                    preNode.right = null;
                    res.add(curNode.val);
                    curNode = curNode.right;
                }
            }
        }
        return res;

(3) Postorder Traversal

List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }

        TreeNode dummy = new TreeNode(0);
        TreeNode preNode = null, curNode = dummy;
        dummy.left = root;

        while (curNode != null) {
            if (curNode.left == null) {
                curNode = curNode.right;
            }
            else {
                preNode = curNode.left;
                while (preNode.right != null && preNode.right != curNode) {
                    preNode = preNode.right;
                }

                // Traversing down
                if (preNode.right == null) {
                    preNode.right = curNode;
                    curNode = curNode.left;
                }
                // Traversing up, reverse the path
                else {
                    TreeNode node = preNode;
                    reverse(curNode.left, preNode);
                    while (node != curNode.left) {
                        res.add(node.val);
                        node = node.right;
                    }
                    res.add(node.val); // node is now equal to curNode.left
                    reverse(preNode, curNode.left);
                    preNode.right = null;
                    curNode = curNode.right;
                }
            }
        }
        return res;
    }

    public void reverse(TreeNode from, TreeNode to) {
        if (from == to) {
            return;
        }

        TreeNode preNode = from, curNode = from.right, nextNode = null;

        while (preNode != to) {
            nextNode = curNode.right;
            curNode.right = preNode;
            preNode = curNode;
            curNode = nextNode;
        }
    }

5. Question Category

PreviousSegment TreeNext94 Binary Tree Inorder Traversal

Last updated 5 years ago

Was this helpful?

This is essentially

DFS is helpful to get the size of subtree:

DFS is helpful to get the height of subtree:

Check if a tree is binary search tree:

Based on the property of Binary Search Tree, we can implement Binary Search to retrieve a value:

Preorder Traversal:

Inorder Traversal:

Postorder Traversal:

Binary Tree Level Order Traversal
Largest BST Subtree
Balanced Binary Tree
Validate Binary Search Tree
Kth Smallest Element in a BST
Serialize and Deserialize Binary Tree,
Recover Binary Search Tree,
Binary Tree Postorder Traversal