LF.51.Insert In Binary Search Tree

本文介绍了如何在二叉搜索树中插入一个新节点,并确保树的性质不变。提供了递归和迭代两种实现方式,详细解释了每种方法的具体步骤。
Insert a key in a binary search tree if the binary search tree does not already contain the key. Return the root of the binary search tree.

Assumptions

There are no duplicate keys in the binary search tree

If the key is already existed in the binary search tree, you do not need to do anything

Examples

        5

      /    \

    3        8

  /   \

 1     4

insert 11, the tree becomes

        5

      /    \

    3        8

  /   \        \

 1     4       11

insert 6, the tree becomes

        5

      /    \

    3        8

  /   \     /  \

 1     4   6    11

 

DFS recursive:

 1 public class Solution {
 2   public TreeNode insert(TreeNode root, int key) {
 3     // Write your solution here
 4     //this is the base case
 5     if (root == null ) {
 6         return new TreeNode(key) ;
 7     }
 8     if (root.key == key){
 9         return root ;
10     }
11     if (root.key > key) {
12         //go to left
13         root.left = insert(root.left, key) ;
14     }
15     if (root.key < key ) {
16         //go to right
17         root.right = insert(root.right, key) ;
18     }
19     //back -> upper -> upper upper to the top then return
20     return root ;
21   }
22 }

 

 

 

 

since this is called tail recursion, you are recommended to do it in interative: time: O(h) space: O(1)

Interative:

 

/*iterative: time o(h) space: o(1)
  note, here requires: Return the root of the binary search tree.
  so you need to maintain the reference of the root
  */
  public TreeNode insert_iter2(TreeNode root, int key) {
    // Write your solution here
    //this is the base case
    TreeNode newNode = new TreeNode(key);
    if (root == null ) {
        return newNode;
    }
    TreeNode curr = root ;
    while(curr != null){
        if (curr.key == key) {
            return root ; //do nothing
        } else if(curr.key < key){
            if (curr.right == null) {
                curr.right = newNode;
                break ;
            } else{
                curr = curr.right ;
            }
        } else {
            if (curr.left == null) {
                curr.left = newNode ;
                break ;
            } else {
                curr = curr.left ;
            }
        }
    }
    //return the root
    return root ;
  }

 

转载于:https://www.cnblogs.com/davidnyc/p/8655269.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值