BST or Inorder

public TreeNode insertIntoBST(TreeNode root, int val) {
    if (root == null) {
        return new TreeNode(val);
    }
    if (val < root.val) {
        root.left = insertIntoBST(root.left, val);
    } else {
        root.right = insertIntoBST(root.right, val);
    }
    return root;
}

public boolean isValidBST(TreeNode root) {
    return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean helper(TreeNode curt, long min, long max) {
    if (curt == null) return true;
    if (curt.val <= min || curt.val >= max) return false;
    return helper(curt.left, min, curt.val) 
        && helper(curt.right, curt.val, max);
}

An upgrade version of 235. Need to output LCA as well as count depth.

Reverse in-order traversal, add the increment to the node and update the increment.

Inorder traversal the tree and maintain a list. Treat the list as a deque or linkedlist. Add nodes to the back, pop first if the first nodes is farther than curt val. Therefore all nodes in the list are the closest to target when the list size is larger than k. When the first node is closer target than current node. It means all results are found, return.

This is similar as sliding window on an array and maintain the closest values.

3 scenarios:

  • L R < root.val

  • root.val < L R

  • L < root.val < R

Solution1. Inorder traversal and store all results in a list

Solution2: Iteration Inorder traversal by using Stack

Solution3: Morris traversal:

Inorder traverse this tree, use pre to record the previous node, at each node check if pre != null && A == null && pre.val >= curt.val. If so, set the A to pre, which means A is a candidate. if pre != null && A != null && pre.val >= curt.val then B is another candidate. For example,

A B

1 2 4 3 5

Then swap the value of A and B.

Two Sum approach: O(n^2)

Set approach: T: O(n) S: O(n)

Last updated