1.问题描述:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
2.思路:样例
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
首先要明确什么是二叉查找树,即为左子树的值小于根节点的值,右子树的值大于根节点的值。所以只需要比较加入节点的值与根节点的值即可,若小于根节点则再看根节点的左子树是否为空,如果为空则直接插在左子树的位置,否则再把根的左子树遍历这个函数。插入节点值大于根节点值时考虑将新节点插入右子树的情况,同左子树。要注意根节点及根节点的左右子树为空的情况~
3.代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
TreeNode* insertNode(TreeNode* root, TreeNode* node) {
// write your code here
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);
}
return root;
}
if(node->val>root->val)
{
if(root->right==NULL)
{ root->right=node;}
else
{ root->right=insertNode(root->right,node);
}
return root;
}
}
};
4.感想:一定别忘了根节点及根节点的左右子树为空的情况呀!