235. 二叉搜索树的最近公共祖先
利用到了搜索二叉树的性质,若两个节点都在左边,那么就向左,如果两个节点都在右边,那么向右遍历,遇到的第一个一个节点在左边一个节点在右边的点就是我们要找的点。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root!=NULL)
return traversal(root,p,q);
else
return NULL;
}
TreeNode *traversal(TreeNode *cur,TreeNode* p,TreeNode* q)
{
if(cur==NULL) return NULL;
if(cur->val>p->val&&cur->val>q->val)
return traversal(cur->left,p,q);
if(cur->val<p->val&&cur->val<q->val)
return traversal(cur->right,p,q);
return cur;
}
};
701.二叉搜索树中的插入操作
这道题其实十分的简单。首先要明确一件事就是我们插入的地方一定是叶子节点而不是某个非叶子结点的位置。而这道题我们就有两种写法了,首先可以有返回值ThreeNode*,也可以没有返回值,那么我们就需要一个节点来保存paraent。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==nullptr)
{
TreeNode *node=new TreeNode(val);
return node;
}
if(root->val>val)
{
root->left=insertIntoBST(root->left,val);
return root;
}
if(root->val<val)
{
root->right=insertIntoBST(root->right,val);
return root;
}
return root;
}
};
450.删除二叉搜索树中的节点
这道题就是在确定递归结束返回值的部分会比较复杂需要确立五种情况。然后在重构结构的时候我们可以参考中序遍历的那个序列,想象一下序列上删除一个节点,那么我们就要把这个节点的左子树的所有节点都放在中序下一个会遍历到的地方的左子树上。
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root==nullptr) return root;
if(root->val==key)
{
if(root->left==nullptr&&root->right==nullptr)
{
delete root;
return nullptr;
}
if(root->left==nullptr&&root->right)
{
auto tmp=root->right;
delete root;
return tmp;
}
if(root->left&&root->right==nullptr)
{
auto tmp=root->left;
delete root;
return tmp;
}
if(root->left&&root->right)
{
TreeNode *cur=root->right;
while(cur->left)
{
cur=cur->left;
}
cur->left=root->left;
auto tmp=root->right;
delete root;
return tmp;
}
}
if(root->val>key) root->left=deleteNode(root->left,key);
if(root->val<key) root->right=deleteNode(root->right,key);
return root;
}
};