Question:
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 null
.
题目意思是给定一个二叉搜索树和在这个搜索树当中的一个节点P,求在中序遍历中p的后续节点。
可以知道:
1、如果这个节点p有右孩子,那么p的后续节点为右子树的的最左值(即最后一个没有左孩子的节点);
2、如果节点p没有右孩子,那就在二叉搜索树中搜索节点p,并在从上往下的查找过程中依次更新记录比p的val值大的节点。
代码如下(参考):
<span style="font-size:14px;">class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if (p -> right) return leftMost(p -> right);
TreeNode* suc = NULL;
while (root) {
if (p -> val < root -> val) {
suc = root;
root = root -> left;
}
else if (p -> val > root -> val)
root = root -> right;
else break;
}
return suc;
}
private:
TreeNode* leftMost(TreeNode* node) {
while (node -> left) node = node -> left;
return node;
}
};</span>