1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. class Solution {
    11. public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
    12. //递归终止条件
    13. if(root == null){
    14. return null;
    15. }
    16. //1:第一步,找到一个大于P的节点
    17. //如果当前结点值 <= p,说明本节点包含其左子树,都不满足大于p,所以要去右子树找到第一个大于p的点
    18. if(root.val <= p.val){
    19. return inorderSuccessor(root.right,p);
    20. }
    21. //到这一步,说明找到了第一个大于p的点。
    22. //2:第二步,找到这个节点的最左的结点,也就是比P的并且是最小的点
    23. TreeNode ans = inorderSuccessor(root.left, p);
    24. //3:返回。如果ans已经null了,说明走到最左面了到头了,他的上一个结点root就是最左面的结点,则返回root
    25. if(ans == null){
    26. return root;
    27. }else {
    28. return ans;
    29. }
    30. }
    31. }