1.描述:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
样例
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
3.代码:
TreeNode* insertNode(TreeNode* root, TreeNode* node) {
if(root == NULL)
{
root = node;
return root;
}
if(node->val < root->val)
{
if(root->left == NULL)
{
root->left = node;
}
else{
root->left = insertNode(root->left, node);
}
}
else{
if(root->right == NULL)
{
root->right = node;
}
else{
root->right = insertNode(root->right, node);
}
}
return root;
}
4.感想:
最早做这个题的时候是做二叉树的时候不小心选错了题,当时还想这题有错误,最后在写这篇博客时才发现了是自己看错题了,现在重新做这题感觉很简单。