Inorder Successor in BST
2016-08-04 09:50
274 查看
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return
最终思想就是,next element分两种,
1. 如果node有右子树,next successor就是右孩子的最左的孩子。
2. 如果node没有右node,那么next successor就是这条树枝向上,最后一个左拐的node。所以,需要用一个node去记录每次左拐,他的parent。
10
/
4
\
5
\
6
\
7
思路,就是如果node有right tree,搜right tree的最左边点,如果没有,那么从root开始搜到p,然后只要左拐,就记录update一下succ,最后找到了,return succ就可以了。
Note: If the given node has no in-order successor in the tree, return
null.
最终思想就是,next element分两种,
1. 如果node有右子树,next successor就是右孩子的最左的孩子。
2. 如果node没有右node,那么next successor就是这条树枝向上,最后一个左拐的node。所以,需要用一个node去记录每次左拐,他的parent。
10
/
4
\
5
\
6
\
7
思路,就是如果node有right tree,搜right tree的最左边点,如果没有,那么从root开始搜到p,然后只要左拐,就记录update一下succ,最后找到了,return succ就可以了。
/** * 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 || p == null) return null; TreeNode succ = null; if(p.right!=null){ return minLeftNode(p.right); } else { while(root.val != p.val){ if(root.val > p.val){ succ = root; root = root.left; } else { // root.val < p.val; root = root.right; } } return succ; } } public TreeNode minLeftNode(TreeNode n) { if(n == null) return null; TreeNode node = n; while(node!=null && node.left!=null){ node = node.left; } return node; } }
相关文章推荐
- LeetCode Inorder Successor in BST
- 1st round, 285 Inorder Successor in BST
- 285. Inorder Successor in BST
- [Lintcode] Inorder Successor in BST
- *Inorder Successor in BST
- 如何用C++递归来查找BST中的根节点的inorder successor
- [leetcode 285] Inorder Successor in BST---查找二叉搜索树中某个节点在中序遍历中的后续节点
- 285. Inorder Successor in BST
- Inorder Successor in BST
- LeetCode-Inorder Successor in BST
- **LeetCode-Inorder Successor in BST
- Inorder Successor in BST 解答
- 285. Inorder Successor in BST
- [LeetCode] Inorder Successor in BST
- [leetCode]Inorder Successor in BST
- [LeetCode]Inorder Successor in BST
- 285. Inorder Successor in BST
- [LeetCode285]Inorder Successor in BST
- Ch4.5: find the (in-order tranversely) successor of a node in BST.
- [刷题]Inorder Successor in BST