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

Lintcode: Insert Node in a Binary Search Tree

时间:2015-03-05 06:50:40      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary search tree  and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.

Example
Given binary search tree as follow:

     2

  /    
1        4

         /   

       3 

after Insert node 6, the tree should be:

     2

  /    
1        4

         /   \ 

       3        6

Challenge
Do it without recursion

Recursion做法:

 1 public class Solution {
 2     /**
 3      * @param root: The root of the binary search tree.
 4      * @param node: insert this node into the binary search tree
 5      * @return: The root of the new binary search tree.
 6      */
 7     public TreeNode insertNode(TreeNode root, TreeNode node) {
 8         // write your code here
 9         if (root == null) return node;
10         if (node == null) return root;
11         TreeNode rootcopy = root;
12         while (root != null) {
13             if (root.val<=node.val && root.right==null) {
14                 root.right = node;
15                 break;
16             }
17             else if (root.val>node.val && root.left==null) {
18                 root.left = node;
19                 break;
20             }
21             else if(root.val <= node.val) root = root.right;
22             else root = root.left;
23         }
24         return rootcopy;
25     }
26 }

Iterative做法:

 1 public class Solution {
 2     /**
 3      * @param root: The root of the binary search tree.
 4      * @param node: insert this node into the binary search tree
 5      * @return: The root of the new binary search tree.
 6      */
 7     public TreeNode insertNode(TreeNode root, TreeNode node) {
 8         // write your code here
 9         if (root == null) return node;
10         if (node == null) return root;
11         TreeNode rootcopy = root;
12         while (root != null) {
13             if (root.val<=node.val && root.right==null) {
14                 root.right = node;
15                 break;
16             }
17             else if (root.val>node.val && root.left==null) {
18                 root.left = node;
19                 break;
20             }
21             else if(root.val <= node.val) root = root.right;
22             else root = root.left;
23         }
24         return rootcopy;
25     }
26 }

 

Lintcode: Insert Node in a Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4314777.html

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