代码随想录 Day23 - 二叉树(九)
作者:jjn0703
- 2023-08-01 江苏
本文字数:889 字
阅读完需:约 3 分钟
669. 修剪二叉搜索树
package jjn.carl.binary_tree;
import commons.TreeNode;
/** * @author Jjn * @since 2023/8/1 16:36 */public class LeetCode669 { public TreeNode trimBST(TreeNode root, int low, int high) { if (root == null) { return null; } if (root.val < low) { return trimBST(root.right, low, high); } if (root.val > high) { return trimBST(root.left, low, high); } root.left = trimBST(root.left, low, high); root.right = trimBST(root.right, low, high); return root; }}
复制代码
108. 将有序数组转换为二叉搜索树
二叉搜索树的中序遍历是升序序列,题目给定的数组是按照升序排序的有序数组,因此可以确保数组是二叉搜索树的中序遍历序列。
package jjn.carl.binary_tree;
import commons.TreeNode;
/** * @author Jjn * @since 2023/8/1 17:08 */public class LeetCode108 { public TreeNode sortedArrayToBST(int[] nums) { return buildTree(nums, 0, nums.length - 1); } private TreeNode buildTree(int[] nums, int left, int right) { if (left > right) { return null; } int mid = left + (right - left) / 2; TreeNode root = new TreeNode(nums[mid]); root.left = buildTree(nums, left, mid - 1); root.right = buildTree(nums, mid + 1, right); return root; }}
复制代码
538. 把二叉搜索树转换为累加树
package jjn.carl.binary_tree;
import commons.TreeNode;
/** * @author Jjn * @since 2023/8/1 17:12 */public class LeetCode538 { private int sum = 0; public TreeNode convertBST(TreeNode root) { if (root != null) { convertBST(root.right); sum += root.val; root.val = sum; convertBST(root.left); } return root; }}
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 7
jjn0703
关注
Java工程师/终身学习者 2018-03-26 加入
USTC硕士/健身健美爱好者/Java工程师.










评论