Given a binary search tree (See Definition) and a node in it, find the in-order successor of that node in the BST.
If the given node has no in-order successor in the tree, return null.
Notice
It's guaranteed p is one node in the given tree. (You can directly compare the memory address to find p)
Example
Given tree = [2,1] and node = 1:
2
/
1
return node 2.
Given tree = [2,1,3] and node = 2:
2
/ \
1 3
return node 3.
Challenge
O(h), where h is the height of the BST.
思路
中序遍历是左根右的顺序。
在某一点root,如果root.val > p.val,说明p在root的左子树。那么我们可以往左继续找p。
这时root就是候选的successor。
在某一点root,如果root.val < p.val,说明p在root的右子树。那么我们保持现在的候选successor。
总结:只要往左走,就更新successor的候选为当前点。
Code
/** * 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) { // write your code here if (root == null) { return root; } TreeNode succ = null; while (root != null) { if (p.val < root.val) { succ = root; root = root.left; } else { root = root.right; } } return succ; } }