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; } }