• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Lintcode: Insert Node in a Binary Search Tree

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         helper(root, node);
12         return root;
13     }
14     
15     public void helper(TreeNode root, TreeNode node) {
16         if (root.val <= node.val && root.right == null) root.right = node;
17         else if (root.val > node.val && root.left == null) root.left = node;
18         else if (root.val <= node.val) helper(root.right, node);
19         else helper(root.left, node);
20     }
21 }

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 }

 

posted @ 2015-03-05 05:00  neverlandly  阅读(1260)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3