zoukankan      html  css  js  c++  java
  • 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:
    
      /    
           4
    
             /   
    
    
    after Insert node 6, the tree should be:
    
      /    
           4
    
             /    
           6
    
    Challenge
    Do it without recursion

    Iterative做法

    public TreeNode insertNode(TreeNode root, TreeNode node) {
            // write your code here
            if (root == null) {
                return node;
            }
            // tmp 不断比较找到最后一个点, 用last记录
            TreeNode tmp = root, last = null;
            while (tmp != null) {
                last = tmp; 
                if (tmp.val > node.val) {
                    tmp = tmp.left;
                } else {
                    tmp = tmp.right;
                }
                
            }
            // 分情况讨论 将node 链接
            
            if (last.val > node.val) {
                    last.left = node;
                } else {
                    last.right = node;
                }
            return root;
    }
    

      

    分治法:

    public TreeNode insertNode(TreeNode root, TreeNode node) {
            if (root == null) {
                return node;
            }
            
            if (root.val > node.val) {
                root.left = insertNode(root.left, node);
            } else {
                root.right = insertNode(root.right, node);
            }
            
            return root;
        }
    

    Recursion做法:

    public class Solution {
        /**
         * @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.
         */
        public TreeNode insertNode(TreeNode root, TreeNode node) {
            // write your code here
            if (root == null) return node;
            if (node == null) return root;
            helper(root, node);
            return root;
        }
        
        public void helper(TreeNode root, TreeNode node) {
            if (root.val <= node.val && root.right == null) root.right = node;
            else if (root.val > node.val && root.left == null) root.left = node;
            else if (root.val <= node.val) helper(root.right, node);
            else helper(root.left, node);
        }
    }
    

      

  • 相关阅读:
    URL域名获取
    SQL Server 索引结构及其使用(二)
    SQL Server 索引结构及其使用(一)[转]
    查询数据库中所有表的数据量、有效数据量以及其它定制数据量
    转:Servlet的url匹配以及url-pattern详解
    转:在MyEclipse下创建Java Web项目 入门(图文并茂)经典教程
    MyEclipse +Servlet 乱码
    MyEclipse +Tomcat 异常操作
    Android Include标签
    转ATL对象类型
  • 原文地址:https://www.cnblogs.com/apanda009/p/7239171.html
Copyright © 2011-2022 走看看