zoukankan      html  css  js  c++  java
  • Lintcode85-Insert Node in a Binary Search Tree-Easy

    85. 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

    Example 1:
    	Input:  tree = {}, node = 1
    	Output:  1
    	
    	Explanation:
    	Insert node 1 into the empty tree, so there is only one node on the tree.
    
    Example 2:
    	Input: tree = {2,1,4,3}, node = 6
    	Output: {2,1,4,3,6}
    	
    	Explanation: 
    	Like this:
    
    
    
    	  2             2
    	 /            / 
    	1   4   -->   1   4
    	   /             /  
    	  3             3   6
    		
    

    Challenge

    Can you do it without recursion?

    思路:

    在树上定位要插入节点的位置。

    1. 如果它大于当前根节点,则应该在右子树中,如果没有右子树则将该点作为右儿子插入;若存在右子树则在右子树中继续定位。
    2. 如果它小于当前根节点,则应该在左子树中,处理同上。

    (二叉查找树中保证不插入已经存在的值)

    二分法代码:

    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;
        }
  • 相关阅读:
    移动web开发框架研究
    Android客户端缓存机制(文字缓存和多媒体文件缓存)
    edittext实现自动查询,刷新listview
    Android属性动画 nineoldandroids
    android 框架LoonAndroid,码农偷懒专用
    待看
    aidl
    国内外DNS服务器地址列表
    js 防止重复点击
    js 模块化
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10715383.html
Copyright © 2011-2022 走看看