二叉查找树

Posted Hesier

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉查找树相关的知识,希望对你有一定的参考价值。

在二叉查找树中插入节点

递归

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;
}

 

以上是关于二叉查找树的主要内容,如果未能解决你的问题,请参考以下文章