一、 669. 修剪二叉搜索树
题目连接:https://leetcode.cn/problems/trim-a-binary-search-tree/
思路:遍历二叉树,比最小是还小的 向root.righ遍历,比最大值还大的root.left遍历,符合条件的正常遍历
/**
* 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 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. 将有序数组转换为二叉搜索树
题目连接:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/
/**
* 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 {
private TreeNode sortedArrayToBST(int[] nums, int left, int right) {
if (left >= right) return null;
int mid = left + ((right - left) / 2);
TreeNode treeNode = new TreeNode(nums[mid]);
treeNode.left = sortedArrayToBST(nums, left, mid);
treeNode.right = sortedArrayToBST(nums, mid + 1, right);
return treeNode;
}
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) return null;
return sortedArrayToBST(nums, 0, nums.length);
}
}
三、 538. 把二叉搜索树转换为累加树
题目连接:https://leetcode.cn/problems/convert-bst-to-greater-tree/
思路:中序遍历,先遍历右节点,记录sum为累加,sum += root.val root.val = sum;
/**
* 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 {
private int sum = 0;
private void convert(TreeNode root) {
if (root == null) return;
convert(root.right);
sum += root.val;
root.val = sum;
convert(root.left);
}
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
}