首页 > 其他 > 详细

二叉查找树

时间:2016-06-10 17:33:11      阅读:216      评论:0      收藏:0      [点我收藏+]

在二叉查找树中插入节点

递归

public TreeNode insertNode(TreeNode root, TreeNode node) {
    if (root == null) {
        return node;
    }
    if (root.val >= node.val) {
        root.left = insertNode(root.left, node);
    }
    if (root.val < node.val) {
        root.right = insertNode(root.right, node);
    }
    return root;
}

 非递归

public TreeNode insertNode(TreeNode root, TreeNode node) {
    if (root == null) {
        return node;
    }

    TreeNode cur = root;
    TreeNode last = null;

    while (cur != null) {
        last = cur;
        if (cur.val > node.val) {
            cur = cur.left;
        } else {
            cur = cur.right;
        }
    }

    if (last != null) {
        if (last.val > node.val) {
            last.left = node;
        } else {
            last.right = node;
        }
    }
    return root;
}

 

二叉查找树

原文:http://www.cnblogs.com/hesier/p/5573859.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!