Inorder Successor in BST

Problem

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return null.

Solution

Recursive Solution

public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) return null;
        if (p.val >= root.val) return inorderSuccessor(root.right, p);
        TreeNode left = inorderSuccessor(root.left, p);
        return left == null ? root : left;
    }
}

Analysis

A typical inorder traversal using recursion
Since it's a BST, we can compare p.val with root.val to locate where the p at of root
This is important because inorder traversal is Left - Root - Right
Therefore, if p is at right, we need to return null if there is no more left subtree of p, otherwise return left subtree of p.right
If p is already at left of current root, we just need to drag root down and see if we can find another left subtree, return root if no left subtree found (left == null)

Here lies the method to find predecessor in inorder traversal:

public TreeNode inorderPredecessor(TreeNode root, TreeNode p) {
    if (root == null) return null;
    if (p.val <= root.val) return inorderPredecessor(root.left, p);
    TreeNode right = inorderPredecessor(root.right, p);
    return right == null ? root : right;
}

results matching ""

    No results matching ""