代码随想录算法训练营第32天|LeetCode701.二叉搜索树中的插入操作
1、LeetCode701.二叉搜索树中的插入操作
https://leetcode.cn/problems/insert-into-a-binary-search-tree/
第一想法:有点复杂,感觉会涉及到旋转之类的操作。一直遍历找到能插入的位置就插入。
递归法
可以不考虑题目中提示所说的改变树的结构的插入方式。
只要遍历二叉搜索树,找到空节点 插入元素就可以了,那么这道题其实就简单了。
- 参数和返回值
TreeNode* insertIntoBST(TreeNode* root, int val)
或无返回值——更复杂,需要额外定义一个parent变量。 - 终止条件
找到节点为空,插入 - 单层逻辑
不需要遍历整棵树
代码(有返回值)
犯错:插入时没有赋值给root->left
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
// 递归1 有返回值
if(root == NULL){
TreeNode* node = new TreeNode(val);
return node;
}
if(root->val > val){
// 往左边插入
root->left = insertIntoBST(root->left, val); //注意这里要赋值给root->left
}
if(root->val < val){
// 往右边插入
root->right = insertIntoBST(root->right, val);
}
// 插入后返回树
return root;
}
};
代码(没有返回值)
需要额外记录parent变量,并及时更新。
class Solution {
public:
// 递归2 没有返回值
TreeNode* parent;//记录父节点
void traversal(TreeNode* root, int val){
if(root == NULL){
TreeNode* node = new TreeNode(val);
if(parent->val < val)
parent->right = node;
else
parent->left = node;
return ;
}
parent = root;//及时更新
if(root->val < val)
traversal(root->right, val);
else
traversal(root->left, val);
return ;
}
TreeNode* insertIntoBST(TreeNode* root, int val) {
// 递归2 没有返回值
if(root == NULL){
TreeNode* node = new TreeNode(val);
return node;
}
traversal(root, val);
return root;
}
};
迭代法
需要使用pre和cur。这一题中parent即cur
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
// 法3 迭代法
if(root == NULL){
TreeNode* node = new TreeNode(val);
return node;
}
TreeNode* parent = NULL;
TreeNode* cur = root;
while(cur){
parent = cur;//注意这里及时更新parent
if(cur->val < val)
cur = cur->right;
else
cur = cur->left;
}
TreeNode* node = new TreeNode(val);
if(parent->val < val)
parent->right = node;
else
parent->left = node;
return root;
}
};