● 669. 修剪二叉搜索树
没做。。。。。。
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在[low,high]范围内
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
108.将有序数组转换为二叉搜索树
思路真的不难,多看吧。。。。。
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return traversal(nums,0,nums.length-1);
}
private TreeNode traversal(int[] nums, int left, int right){
if(left>right){
return null;
}
int m = left+(right-left)/2;
TreeNode root = new TreeNode(nums[m]);
root.left = traversal(nums,left,m-1);
root.right = traversal(nums,m+1,right);
return root;
}
}
● 538.把二叉搜索树转换为累加树
pre被定义成了int,而不是treenode;
class Solution {
private int pre = 0;
public TreeNode convertBST(TreeNode root) {
traversal(root);
return root;
}
private void traversal(TreeNode cur){
if(cur==null) return ;
traversal(cur.right);
cur.val+=pre;
pre=cur.val;
traversal(cur.left);
}
}