一.题目描述
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项 You can assume there is no duplicate values in this tree + node.
样例 给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
二.解题思路
若当前的二叉查找树为空,则待插入的元素为根节点,若插入的节点值小于根节点值,则将节点插入到左子树中,若插入的节点值大于根节点值,则将节点插入到右子树中,利用递归依次向下比较,最后返回给定根节点.
三.实现代码
/**
* 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(root->val>node->val)
{ if(root->left==NULL)
root->left=node;
else
insertNode(root->left,node); }
else
{ if(root->right==NULL)
root->right=node;
else
insertNode(root->right,node); }
return root;
}
};
四.感想
/**
* 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(root->val>node->val)
{ if(root->left==NULL)
root->left=node;
else
insertNode(root->left,node); }
else
{ if(root->right==NULL)
root->right=node;
else
insertNode(root->right,node); }
return root;
}
};
一开始我没有考虑左子树或右子树为空的情况,结果就一直wrong anwser,如果不判断是否为空,则当空的时候节点和root连接不起来,返回的一直是原来给定的二叉树.