701. Insert into a Binary Search Tree
Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
For example,
Given the tree:
4
/ \
2 7
/ \
1 3
And the value to insert: 5
You can return this binary search tree:
4
/ \
2 7
/ \ /
1 3 5
This tree is also valid:
5
/ \
2 7
/ \
1 3
\
4
思路:没什么好说,直接按二叉搜索树的性质找到待插入的地方,插入即可。
python,
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
p = root
while True:
if val > root.val:
if(root.right):
root = root.right
else:
t = TreeNode(val)
root.right = t
return p;
else:
if root.left:
root = root.left
else:
t = TreeNode(val)
root.left = t
return p;
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
int rootVal = root->val;
TreeNode* p = root;
while(1){
if(val > rootVal ){//查找右子树
if(p->right){//没有到头
p = p->right;
rootVal = p->val;
}
else{//p->right == NULL
p->right = new TreeNode(val);
break;
}
}
else{//查找左子树
if(p->left){//没有到头
p = p->left;
rootVal = p->val;
}
else{
p->left = new TreeNode(val);
break;
}
}
}
return root;
}
};
结果:
这里得吐槽以下,C++的代码我写了一下午,一直debug,原因就是涉及到了指针,我一直报runtime error,访问了非法地址,一个原因是当找到待插入的点,p指向待插入路径上的叶子节点时,应该是p->right = new TreeNode(val)
,而不是p = p->right, p = new TreeNode(val)
还有一个报错使用malloc,还不知道是什么原因,得好好复习一下指针的部分!