您的位置:首页 > 其它

1st round, 285 Inorder Successor in BST

2017-02-10 13:46 309 查看
一道看上去简单,但无从下手的题目。。。不是那种典型的根据叶子节点递归的题,而是要返回某个节点的题!!!卧槽,我发现套路了,就是和那到找最低共同祖先节点的题一个道路啊!!也是返回节点,那么我们就要生成一个节点,方式就是通过这个方法本身,然后通过判断是节点是否是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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: