码迷,mamicode.com
首页 > 其他好文 > 详细

[lintcode easy]Insert Node in a Binary Search Tree

时间:2015-12-03 07:10:16      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

Insert Node in a Binary Search Tree

Example

Given binary search tree as follow, after Insert node 6, the tree should be:

  2             2
 / \           / 1   4   -->   1   4
   /             / \ 
  3             3   6
Challenge

Can you do it without recursion?

 

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
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)
        {
            root=node;
            return root;
        }
        
        TreeNode temp=root;
        TreeNode last=null;
        
        while(temp!=null)
        {
           last=temp;
           if(node.val<temp.val)
           {
              temp=temp.left;
           }
           else
           {
               temp=temp.right;
           }
        }
        
        if(last!=null)
        {
            if(last.val>node.val)
            {
                last.left=node;
            }
            else
            {
                last.right=node;
            }
        }
        return root;
    }
}

 

[lintcode easy]Insert Node in a Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5014954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!