链接
https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/
耗时
解题:21 min
题解:6 min
题意
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据保证,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
思路
利用二叉搜索树(BST)性质,从根节点开始,将当前节点值和插入值比较,如果插入值小就去左子树找,否则就去右子树找,直到找到第一个空节点,新建一个树节点,替换这个空节点位置。
时间复杂度:
O
(
n
)
O(n)
O(n),最坏情况下需遍历整棵树
AC代码
1. dfs
class Solution {
private:
int val;
public:
void dfs(TreeNode* root) {
if(val < root->val) {
if(root->left != NULL) {
dfs(root->left);
}
else {
TreeNode* s = new TreeNode(val);
root->left = s;
}
}
else if(val > root->val) {
if(root->right != NULL) {
dfs(root->right);
}
else {
TreeNode* s = new TreeNode(val);
root->right = s;
}
}
}
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == NULL) return new TreeNode(val);
this->val = val;
dfs(root);
return root;
}
};
2. 迭代
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == NULL) return new TreeNode(val);
TreeNode* now = root;
TreeNode* parent;
bool isleft = false;
while(now != NULL) {
parent = now;
if(val < now->val) {
now = now->left;
isleft = true;
}
else {
now = now->right;
isleft = false;
}
}
TreeNode* s = new TreeNode(val);
if(isleft) parent->left = s;
else parent->right = s;
return root;
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)