新手算法学习之路----二叉树(在一个二叉查找树中插入一个节点)

题目:给定一棵二叉查找树和一个新的树节点,将节点插入到树中。

          你需要保证该树仍然是一棵二叉查找树。

给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:

  2             2
 / \           / \
1   4   -->   1   4
   /             / \ 
  3             3   6
需要搞清楚定义:二叉排序树或者是一棵空树;或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;

Java代码:
/**
 * 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){
            return node;
        }
        if(root.val>node.val){                       //这个树里面没有重复的数,所以无需考虑root.val == node.val的情况
            root.left = insertNode(root.left, node);  //待插入值肯定在左右子树的叶子几点上面
        }else{
            root.right = insertNode(root.right,node);
        }
        return root;//最后返回的root值为根节点,每次递归后就要返回当前的root值,以备上一层使用,最后返回整个树的根节点
    }
    
}

 

posted @ 2017-07-26 11:16  JunLiu37  阅读(3866)  评论(0编辑  收藏  举报