【Lintcode】85. Insert Node in a Binary Search Tree

题目地址:

https://www.lintcode.com/problem/insert-node-in-a-binary-search-tree/description

给定一棵BST,向其插入一个node,返回插入完后的树根。代码如下:

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 (node.val < root.val) {
            root.left = insertNode(root.left, node);
        } else if (node.val > root.val) {
            root.right = insertNode(root.right, node);
        }
        
        return root;
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

时空复杂度 O ( h ) O(h)

发布了387 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105450430