1st round, 285 Inorder Successor in BST

一道看上去简单,但无从下手的题目。。。不是那种典型的根据叶子节点递归的题,而是要返回某个节点的题!!!卧槽,我发现套路了,就是和那到找最低共同祖先节点的题一个道路啊!!也是返回节点,那么我们就要生成一个节点,方式就是通过这个方法本身,然后通过判断是节点是否是null,来进行判断

NB!另外一道题的链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/


/**
 * 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(root==null) return null;
        if(root.val<=p.val){
            return inorderSuccessor(root.right, p);
        }else{
            TreeNode left=inorderSuccessor(root.left, p);        
            return left==null? root: left; 
        }
    }
}

// when I wrote the code, it is kind of confusing to complete the last condition, the else part... since this part is going to be called by itself, so write the recursive function is sometime tricky, since you constructing the whole part, but at the same time you have to consider when being called which part is going to be used.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值