my solution java


  • 0
    C
    public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if(p.right != null) return findMin(p.right);
        TreeNode parent = findParent(root, p);
        while(parent != null && parent.right == p) {
            p = parent;
            parent = findParent(root, p);
        }
        return parent;
    }
    public TreeNode findMin(TreeNode root) {
        if(root.left == null) 
            return root;
        return findMin(root.left);
    }
    
    public TreeNode findParent(TreeNode root, TreeNode node) {
        if(root.left == node || root.right == node)
            return root;
        if(node.val > root.val) return findParent(root.right, node);
        if(node.val < root.val) return findParent(root.left, node);
        return null;
    }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.