一、修剪二叉搜索树(LeetCode669)
递归
/**
* 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){
TreeNode right = trimBST(root.right,low,high);
return right;
}
if(root.val > high){
TreeNode left = trimBST(root.left,low,high);
return left;
}
root.left = trimBST(root.left,low,high);
root.right = trimBST(root.right,low,high);
return root;
}
}
二、将有序数组转换为二叉搜索树(LeetCode108)
递归
/**
* 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) {
return travesal(nums,0,nums.length-1);
}
TreeNode travesal(int[] nums,int left,int right){
if(left > right){
return null;
}
// int mid = (left + right) / 2; //数组可能会越界
int mid = left + ((right - left) >> 1);//如果数组长度为偶数,中间位置有两个元素,取靠左边的,另一个就是避免数组越界
TreeNode root = new TreeNode(nums[mid]);
root.left = travesal(nums,left,mid-1);
root.right = travesal(nums,mid+1,right);
return root;
}
}
三、把二叉搜索树转换为累加树(LeetCode538)
递归
/**
* 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 {
int pre = 0;
public TreeNode convertBST(TreeNode root) {
travesal(root);
return root;
}
void travesal(TreeNode cur){
if(cur == null) return ;
travesal(cur.right);
cur.val += pre;
pre = cur.val;
travesal(cur.left);
}
}

被折叠的 条评论
为什么被折叠?



