Hey, do we have to consider nodes with equal value?


  • 0
    C
    public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if(p.right!=null) return findSmallest(p.right);
        TreeNode temp=root;
        Stack<TreeNode> stack=new Stack<>();
        while(temp!=p){
            stack.push(temp);
            temp=p.val<temp.val?temp.left:temp.right;
        }
        while(!stack.isEmpty()){
            TreeNode result=stack.pop();
            if(result.val>p.val) return result;
        }
        return null;
    }
    public TreeNode findSmallest(TreeNode root){
        if(root.left!=null) return findSmallest(root.left);
        return root;
    }
    

    }


Log in to reply
 

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