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

      

  • 相关阅读:
    数据库中的LEFT JOIN 个人理解
    C++ 类的继承方式
    KMP字符串匹配算法
    C++ 运算符重载_加号
    Pin API INS
    Python 爬虫爬取多页数据
    Pin
    NO.12 13 章 字符串&扩展(哈希、KMP、分块、BIT)
    NO.11章 DP(递归递推、最大连续子序列和、LIS、LCS、最长回文子串、DAG、背包)
    NO.10章 图(遍历、最短路、生成树、拓扑、关键路径)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7239171.html
Copyright © 2020-2023  润新知