码迷,mamicode.com
首页 > 其他好文 > 详细

LF.51.Insert In Binary Search Tree

时间:2018-03-27 10:23:32      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:sum   cat   new   cas   read   amp   treenode   log   ted   

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(n) space: O(1)

Interative:

 

LF.51.Insert In Binary Search Tree

标签:sum   cat   new   cas   read   amp   treenode   log   ted   

原文地址:https://www.cnblogs.com/davidnyc/p/8655269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!