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

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

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

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

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

Java代码:2 2 / \ / \ 1 4 --> 1 4 / / \ 3 3 6
/**
 * 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值,以备上一层使用,最后返回整个树的根节点
    }
    
}
相关文章
相关标签/搜索