2021.11.21 - SX07-30.二叉搜索树中的插入操作

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 思路

(1) 模拟法

  • 利用递归找到插入位置插入即可。

3. 代码

import javax.naming.ldap.PagedResultsControl;

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

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);
        }
        insert(root, val);
        return root;
    }

    private void insert(TreeNode root, int val) {
    
    
        if (val < root.val) {
    
    
            if (root.left == null) {
    
    
                root.left = new TreeNode(val);
            } else {
    
    
                insert(root.left, val);
            }
        } else {
    
    
            if (root.right == null) {
    
    
                root.right = new TreeNode(val);
            } else {
    
    
                insert(root.right, val);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121456761