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.
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.
相关文章推荐
- Medium 285题 Inorder Successor in BST
- 285. Inorder Successor in BST
- 285. Inorder Successor in BST
- 285. Inorder Successor in BST
- 285. Inorder Successor in BST
- [leetcode 285] Inorder Successor in BST---查找二叉搜索树中某个节点在中序遍历中的后续节点
- 285. Inorder Successor in BST
- [LeetCode285]Inorder Successor in BST
- 285. Inorder Successor in BST
- 285. Inorder Successor in BST
- [LeetCode] Inorder Successor in BST
- 285. Inorder Successor in BST
- Inorder Successor in Binary Search Tree BST中找中序遍历的后继节点
- 285. Inorder Successor in BST
- Ch4.5: find the (in-order tranversely) successor of a node in BST.
- Inorder Successor in BST
- [LeetCode]Inorder Successor in BST
- [Lintcode] Inorder Successor in BST
- *Inorder Successor in BST
- [Locked] Inorder Successor in BST