java simple solution


  • 0
    Z

    /**

    • Definition for a binary tree node.

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {

       if(p == null) {
           return null;
       }
       
       if(p.right != null) {
           p = p.right;
           
           while(p.left != null) {
               p = p.left;
           }
           
           return p;
       }
       
       TreeNode ans = null;
       
       while(root.val != p.val) {
           if(root.val > p.val) {
               ans = root;
               root = root.left;
           } else {
               root = root.right;
           }
       }
       
       return ans;
      

      }
      }


Log in to reply
 

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