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);
        }
    }
    

      

  • 相关阅读:
    Struts2拦截器的底层实现(AOP思想)
    JFreeChart的使用
    struts2与servlet的耦合
    谷歌地图:使用多边形自动形成类PolygonCreator
    struts2 中的 addActionError 、addFieldError、addActionMessage方法的区别
    Struts2的声明式异常处理
    Java synchronized 详解
    [转载]C# 编写SQL SERVER 2005 的存储过程
    调试基于clr管理的sqlserver存储过程
    sqlserver中调用.net中的dll
  • 原文地址:https://www.cnblogs.com/apanda009/p/7239171.html
Copyright © 2011-2022 走看看