本题要求二叉搜索树中两结点的最近公共祖先,相对于根结点这两个结点的位置有三种情况:全部在左侧、全部在右侧、位于两侧,因此迭代地遍历二叉搜索树,当位于两侧时返回该结点,该结点即为最近公共祖先。
具体代码如下:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root)
{
if(root->val>p->val&&root->val>q->val)
{
root=root->left;
}
else if(root->val<p->val&&root->val<q->val)
{
root=root->right;
}
else{
return root;
}
}
return NULL;
}
};
该题要在二叉搜索树中插入结点,可用递归和迭代两种方法,核心思想就是将该结点插入到叶子结点中,因此重点在于通过对二叉搜索树的遍历找到该结点上一层的结点。
具体代码如下:
迭代法:
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
TreeNode*t=new TreeNode(val);
if(root==NULL)
{
return t;
}
TreeNode*cur=root;
while(cur)
{
if(val>cur->val&&cur->right!=NULL)
{
cur=cur->right;
}
else if(val<cur->val&&cur->left!=NULL)
{
cur=cur->left;
}
else if(cur->right==NULL&&val>cur->val)
{
cur->right=t;
return root;
}
else if(cur->left==NULL&&val<cur->val)
{
cur->left=t;
return root;
}
}
return root;
}
};
递归法:
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==NULL)
{
TreeNode*t=new TreeNode(val);
return t;
}
if(root->val>val)
{
root->left=insertIntoBST(root->left,val);
}
if(root->val<val)
{
root->right=insertIntoBST(root->right,val);
}
return root;
}
};
该题要求删除二叉搜索树的结点,操作与上一题类似,只是在递归法中对于删除结点的操作要更加复杂,结点类型分为五种:左空右空、左空右不空、左不空右空、左不空右不空、结点为空,针对这五种结点类型返回不同的结点,其中左不空右不空可以先化为左空右不空的类型再返回右子树根结点。
具体代码如下:
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root==NULL)
{
return NULL;
}
if(root->val==key)
{
if(root->left==NULL&&root->right==NULL)
{
return NULL;
}
else if(root->left!=NULL&&root->right==NULL)
{
return root->left;
}
else if(root->left==NULL&&root->right!=NULL)
{
return root->right;
}
else
{
TreeNode*cur=root->right;
while(cur->left)
{
cur=cur->left;
}
cur->left=root->left;
return root->right;
}
}
if(root->val>key)
{
root->left=deleteNode(root->left,key);
}
if(root->val<key)
{
root->right=deleteNode(root->right,key);
}
return root;
}
};
文章介绍了如何在LeetCode中解决二叉搜索树相关问题,包括第235题的最近公共祖先、第701题的插入结点(递归和迭代方法)、以及第450题的删除结点,详细展示了代码实现和操作策略。
120

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



