85. 在二叉查找树中插入节点(二叉搜索树)

在树中插入或删除节点,和链表相似。


给定一棵二叉查找树和一个新的树节点,将节点插入到树中。

你需要保证该树仍然是一棵二叉查找树。

样例

给出如下一棵二叉查找树,在插入节点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;
    }
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值