二叉搜索树中的插入操作 (Insert into a Binary Search Tree)

 

思路:

// @Title: 二叉搜索树中的插入操作 (Insert into a Binary Search Tree)
// @Author: qisiii
// @Date: 2024-09-16 16:27:59
// @Runtime: 0 ms
// @Memory: 44 MB
// @comment: 
// @flag: 
/**
 * 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);
        }
        if(val>root.val){
            root.right=insertIntoBST(root.right,val);
        }else if(val<root.val){
            root.left=insertIntoBST(root.left,val);
        }
        return root;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18