Inorder Predecessor in BST

mail@pastecode.io avatar
unknown
java
2 years ago
470 B
0
Indexable
Never
public class Solution {
    TreeNode predecessor = null;

    public TreeNode inorderPredecessor(TreeNode root, TreeNode p) {
        helper(root, p);
        return predecessor;
    }

    void helper(TreeNode root, TreeNode p) {
        if (root == null || p == null) {
            return;
        }

        if (root.val < p.val) {
            predecessor = root;
            helper(root.right, p);
        } else {
            helper(root.left, p);
        }
    }
}