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

Title address:

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

Given a BST, insert a node into it and return the root of the tree after insertion. code show as below:

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

Space-time complexity THE ( h ) O(h)

Published 387 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105450430