设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。
示例 1:
输入: root = [2,1,3], p = 1
2
/ \
1 3输出: 2
示例 2:
输入: root = [5,3,6,2,4,null,null,1], p = 6
5
/ \
3 6
/ \
2 4
/
1输出: null
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/successor-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
暴力做法:非递归中序遍历
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if(!root) {
return nullptr;
}
vector<TreeNode*> TreeNodeArry;
stack<TreeNode*> stackTree;
TreeNode* cur = root;
while(cur || !stackTree.empty()) {
while(cur) {
stackTree.push(cur);
cur = cur->left;
}
cur = stackTree.top();
stackTree.pop();
TreeNodeArry.push_back(cur);
cur = cur->right;
}
int n = TreeNodeArry.size();
if(TreeNodeArry[n - 1] == p) {
return nullptr;
}
for(int i = 0; i < n - 1; i ++) {
if(TreeNodeArry[i] == p) {
cur = TreeNodeArry[i + 1];
}
}
return cur;
}
};
考虑二叉搜索树的性质
递归版
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if(root == nullptr) {
return nullptr;
}
if(root->val <= p->val) {
return inorderSuccessor(root->right, p);
} else {
TreeNode* res = inorderSuccessor(root->left, p);
return res ? res : root;
}
}
};
非递归版
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if(root == nullptr) return nullptr;
if(p->right != nullptr) {
p = p->right;
while(p->left) {
p = p->left;
}
return p;
}
TreeNode* res = nullptr;
while(root != p) {
if(p->val > root->val) {
root = root->right;
} else {
res = root;
root = root->left;
}
}
return res;
}
};
本文介绍了一种寻找二叉搜索树中指定节点中序后继的方法,包括暴力解法(非递归中序遍历)、递归解法及非递归解法,并提供了详细的算法实现。
203

被折叠的 条评论
为什么被折叠?



