跳转至

2022/01/12 - 701. Insert into a Binary Search Tree

701. Insert into a Binary Search Tree - Medium

Description

701. Insert into a Binary Search Tree

You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

这道题已经很简单了,二叉搜索树,左子节点比自己小,右子节点比自己大。

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);
        TreeNode dummy = root;
        insert(root, val);
        return dummy;
    }

    public void insert(TreeNode root, int val) {
        if (root == null) return;
        int n = root.val;
        if (val >= n) {
            if (root.right != null) {
                insert(root.right, val);
            } else {
                root.right = new TreeNode(val);
                return;
            }
        } else {
            if (root.left != null) {
                insert(root.left, val);
            } else {
                root.left = new TreeNode(val);
                return;
            }
        }
    }
}

评论

回到页面顶部