欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > 数据结构与算法之二叉树: LeetCode 701. 二叉搜索树中的插入操作 (Ts版)

数据结构与算法之二叉树: LeetCode 701. 二叉搜索树中的插入操作 (Ts版)

2025/10/21 7:45:49 来源:https://blog.csdn.net/Tyro_java/article/details/145091772  浏览:    关键词:数据结构与算法之二叉树: LeetCode 701. 二叉搜索树中的插入操作 (Ts版)

二叉搜索树中的插入操作

  • https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/

描述

  • 给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value ,将值插入二叉搜索树
  • 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同
  • 注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可
  • 你可以返回 任意有效的结果

示例 1

输入:root = [4,2,7,1,3], val = 5
输出:[4,2,7,1,3,5]

解释:另一个满足题目要求可以通过的树是:

示例 2

输入:root = [40,20,60,10,30,50,70], val = 25
输出:[40,20,60,10,30,50,70,null,null,25]

示例 3

输入:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
输出:[4,2,7,1,3,5]

提示

  • 树中的节点数将在 [0, 1 0 4 10^4 104]的范围内
  • - 1 0 8 10^8 108 <= Node.val <= 1 0 8 10^8 108
  • 所有值 Node.val 是 独一无二 的
  • - 1 0 8 10^8 108 <= val <= 1 0 8 10^8 108
  • 保证 val 在原始BST中不存在

Typescript 版算法实现


1 ) 方案1:模拟

/*** Definition for a binary tree node.* class TreeNode {*     val: number*     left: TreeNode | null*     right: TreeNode | null*     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {*         this.val = (val===undefined ? 0 : val)*         this.left = (left===undefined ? null : left)*         this.right = (right===undefined ? null : right)*     }* }*/function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {if (root === null) return new TreeNode(val);let pos = root;while (pos !== null) {if (val < pos.val) {if (pos.left === null) {pos.left = new TreeNode(val);break;} else {pos = pos.left;}} else {if (pos.right === null) {pos.right = new TreeNode(val);break;} else {pos = pos.right;}}}return root;
};

2 ) 方案2:递归

/*** Definition for a binary tree node.* class TreeNode {*     val: number*     left: TreeNode | null*     right: TreeNode | null*     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {*         this.val = (val===undefined ? 0 : val)*         this.left = (left===undefined ? null : left)*         this.right = (right===undefined ? null : right)*     }* }*/function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {// 如果当前树为空,说明找到了插入位置,创建新节点并返回if (!root) return new TreeNode(val);// 如果要插入的值小于当前节点的值,在左子树中进行插入操作if (val < root.val) {root.left = insertIntoBST(root.left, val);} else {// 如果要插入的值大于等于当前节点的值,在右子树中进行插入操作root.right = insertIntoBST(root.right, val);}// 返回当前节点,保持树的结构return root;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词