Leetcode Index

701.Insert Into a Binary Search Tree

701.Insert Into a Binary Search Tree

难度:Medium

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

First, we need to locate the position to insert, then insert it. Show codes:

/**
* 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) {
TreeNode* cur=root;
TreeNode* newNode = new TreeNode(val);
while(true)
{
if(cur->val > val )
{
if(cur->left )
cur=cur->left;
else
{
cur->left=newNode;
break;
}
}
else
{
if(cur->right)
cur=cur->right;
else
{
cur->right=newNode;
break;
}
}
}
return root;
}
};

执行用时 :88 ms, 在所有 C++ 提交中击败了99.16%的用户 内存消耗 :32.8 MB, 在所有 C++ 提交中击败了87.32%的用户