leetcode-701.二叉搜索树中的插入操作 | LIXI.FUN
0%

leetcode-701.二叉搜索树中的插入操作

题目链接

701. 二叉搜索树中的插入操作

代码

  1. 递归

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
    if (root == null) {
    return new TreeNode(val);
    }

    if (root.val > val) {
    root.left = insertIntoBST(root.left, val);
    } else {
    root.right = insertIntoBST(root.right, val);
    }

    return root;
    }
    }
  2. 迭代

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
    if (root == null) {
    return new TreeNode(val);
    }

    TreeNode parent = root;
    TreeNode node = root;

    while (node != null) {
    parent = node;
    node = node.val > val ? node.left : node.right;
    }

    if (parent.val > val) {
    parent.left = new TreeNode(val);
    } else {
    parent.right = new TreeNode(val);
    }

    return root;
    }
    }

复杂度分析

  • 时间复杂度: O(n)
  • 空间复杂度: O(1)
觉得有收获就鼓励下作者吧