在树中插入或删除节点,和链表相似。
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
思路:根据二叉查找树的性质,当node值大于结点值时,则遍历其右子树,否则遍历其左子树。
代码:
注意二叉查找树不是平衡树,不需要保证左右子树深度,在合适的叶子结点处插入即可。
递归写法:
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
TreeNode*pre=root;
if(pre==NULL)
{ pre=node;
return pre;}
if(pre->val<node->val)
pre->right=insertNode(pre->right,node);
else
pre->left= insertNode(pre->left,node);
return root;
}
};
非递归写法:
注意其中的return root必须写。
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;
}
TreeNode*cur=root;
while(cur!=NULL)
{
if(cur->val<node->val)
{ if(cur->right==NULL)
{cur->right=node;
return root;}//必须写return root不然将陷入无限循环中
cur=cur->right;
}
else
{ if(cur->left==NULL)
{ cur->left=node;
return root;}
cur=cur->left;
}
}
return root;
}
};