问题描述:
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 保证原始二叉搜索树中不存在新值。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
例如,
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insert-into-a-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果:
代码描述:
思路:选择第一种插入方式,简单易懂。先走到最底层,找到那个节点,然后判断左边插还是右边插即可。
/**
* 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) {
if(root == NULL)
{
root->val = val;
return root;
}
TreeNode* temp = root;
TreeNode* parent = root;
while(temp != NULL)
{
parent = temp;
temp = temp->val > val ? temp->left:temp->right;
}
if(parent->val > val)
parent->left = new TreeNode(val);
else
parent->right = new TreeNode(val);
return root;
}
};