/**
* 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;
}
}
/**
* 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 sortedArrayToBST(int[] nums) {
if(nums.length == 0){
return null;
}
return sortedArrayToBST(nums,0,nums.length-1);
}
public TreeNode sortedArrayToBST(int[] nums,int left,int right) {
if(left > right){
return null;
}
int mid = (left + right) / 2;
TreeNode cur = new TreeNode(nums[mid]);
cur.left = sortedArrayToBST(nums,left,mid-1);
cur.right = sortedArrayToBST(nums,mid+1,right);
return cur;
}
}
538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)
/**
* 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 convertBST(TreeNode root) {
if(root == null){
return null;
}
convertBST(root,0);
return root;
}
public int convertBST(TreeNode root,int sum) {
if(root == null){
return sum;
}
int right = convertBST(root.right, sum);
root.val = root.val + right;
return convertBST(root.left, root.val);
}
}