LeetCode-701. Insert into a Binary Search Tree
原创
©著作权归作者所有:来自51CTO博客作者ReignsDu的原创作品,请联系作者获取转载授权,否则将追究法律责任
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:
This tree is also valid:
题解:
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (root == NULL) {
return new TreeNode(val);
}
TreeNode *t = root, *pre = NULL;
while (t != NULL) {
pre = t;
if (t->val > val) {
t = t->left;
}
else if (t->val < val) {
t = t->right;
}
}
if (pre->val > val) {
pre->left = new TreeNode(val);
}
else if (pre->val < val) {
pre->right = new TreeNode(val);
}
return root;
}
};