Day22 二叉树第八天
LeetCode 235.二叉搜索树的最近公共祖先
同样是找最近公共祖先,二叉搜索树就会简单的多,因为我们可以利用二叉树值的特性,通过大小关系就能判断。只要从上往下第一个介于p,q之间的值,就一定是最近公共节点,因为继续往下一定会错过其中一个。
解法1:递归
经典递归法。
class Solution {
private:
TreeNode* traversal(TreeNode* cur, TreeNode* p, TreeNode* q) {
if (cur == NULL) return cur;
if (cur->val > p->val && cur->val > q->val) { // 左
TreeNode* left = traversal(cur->left, p, q);
if (left) return left;
}
if (cur->val < p->val && cur->val < q->val) { // 右
TreeNode* right = traversal(cur->right, p, q);
if (right) return right;
}
return cur;
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return traversal(root, p, q);
}
};
解法2:迭代
迭代法的代码也非常简单,因为二叉搜索树已经为我们指明了遍历的方向。
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;
}
};
LeetCode 701.二叉搜索树中的插入操作
在二叉搜索树中插入的位置一定可以是叶子结点。
递归调用时,我们用父节点把他的返回值接住,这样就完成了新节点与叶子结点的连接。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(!root) return new TreeNode(val);
if(root->val < val)
root->right=insertIntoBST(root->right,val);
else root->left=insertIntoBST(root->left,val);
return root;
}
};
LeetCode 450.删除二叉搜索树中的节点
删除节点与前面的题相比就困难了许多,因为有五种不同的情况,我们都要做不同的操作。
仔细分开五种情况,最关键的是最后一种情况,要把左子树插到右子树的最左下角的节点的左孩子的位置,也就是中序遍历的后继位置。
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root) return root;//1.没有找到节点
if(root->val==key){//2.删除的是叶子结点
if(!root->left && !root->right){
delete root;
return NULL;//返回NULL给上一层
}
else if(!root->left){//3.删除节点的的左孩子为空,用右孩子替代它
auto node=root->right;
delete root;
return node;
}
else if(!root->right){//4.删除节点的的右孩子为空,用左孩子替代它
auto node=root->left;
delete root;
return node;
}
else{//5.左右孩子均不为空,用右孩子替代它,左子树插入到右子树最左下角的节点左边
TreeNode* cur=root->right;
while(cur->left) cur=cur->left;//找到右子树的最左下角节点
cur->left=root->left;//把要删除节点的左子树插入到cur的左孩子
TreeNode* tmp=root; //root节点临时保存用来删除
root=root->right; //用root的右孩子替代root
delete tmp; //删除root
return root;
}
}
if(root->val > key) root->left=deleteNode(root->left,key);
if(root->val < key) root->right=deleteNode(root->right,key);
return root;
}
};
越来越难了呀,哥们。