leetcode链接
代码随想录链接
一刷状态:通过
寻找在q和p的值区间内的节点,就是二叉搜索树的最近公共祖先。注意判断条件,如果root->val 均大于q和p的值,则向左搜索,反之则向右搜索。
递归法
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;
if(root->val>p->val&&root->val>q->val) return lowestCommonAncestor(root->left, p, q);
if(root->val<q->val&&root->val<p->val) return lowestCommonAncestor(root->right, p, q);
return root;
}
};
迭代法
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;
while(root)
{
if(root->val>p->val&&root->val>q->val) root = root->left;
else if(root->val<q->val&&root->val<p->val) root = root->right;
else return root;
}
return NULL;
}
};
leetcode链接
代码随想录链接
一刷状态:通过
遍历到插入的点,插入值
递归法
判断向左还是向右递归,将递归返回的结果,使用左右孩子去接,这样子相当于对树实现分治,完成插入。
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);
}
else if(root->val<val)
{
root->right = insertIntoBST(root->right, val);
}
return root;
}
};
迭代法
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
TreeNode* node = new TreeNode(val);
if(root==nullptr) return node;
TreeNode* pre = nullptr;
TreeNode* cur = root;
while(cur)
{
pre = cur;
if(cur->val>val) cur = cur->left;
else if(cur->val<val) cur = cur->right;
}
if(pre->val>val) pre->left = node;
else if(pre->val<val) pre->right = node;
return root;
}
};
leetcode链接
代码随想录链接
一刷状态:未通过(思路不清晰)
分情况讨论:
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
// 1.未找到删除的节点
if(root==nullptr) return nullptr;
if(root->val==key)
{
// 2.删除节点是叶子节点
if(root->left==nullptr&&root->right==nullptr)
{
delete root;
return nullptr;
}
// 3.删除的节点只有左孩子
else if(root->left!=nullptr&&root->right==nullptr)
{
TreeNode* node = root->left;
delete root;
return node;
}
// 4.删除的节点只有右孩子
else if(root->right!=nullptr&&root->left==nullptr)
{
TreeNode* node = root->right;
delete root;
return node;
}
// 5.删除的节点有左右孩子
else
{
TreeNode* cur = root->right;
while(cur->left) cur = cur->left;
cur->left = root->left;
TreeNode* node = root->right;
delete root;
return node;
}
}
if(root->val>key) root->left = deleteNode(root->left, key);
if(root->val<key) root->right = deleteNode(root->right, key);
return root;
}
};