题目:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例:
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
代码:
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;
}
}
};
思想:若树为空,则根节点为插入点。若插入节点值比根小,若根的左子树为空,则该点位插入点,否则,递归判断整个左子树。若插入节点值比根大,对根的右子树相同操作即可完成插入。