代码随想录刷题Day21
·
669. 修剪二叉搜索树
/**
* 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;
}
//比low小,修剪左枝,找右枝符合范围的结点
if(root.val < low ){
return trimBST(root.right,low,high);
}
//比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;
}
}
这道题感觉理解时候有点抽象(回顾时多思考一下),遇到在合理范围内的结点,则进行保留(return root;),比low小,这个结点用其右孩子代替;比high大,这个结点用其左孩子代替,一直递归。
108. 将有序数组转换为二叉搜索树
/**
* 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 sortedArrayToBST(nums, 0 , nums.length-1);
}
//不断选取区间中间的那个数构造结点
public TreeNode sortedArrayToBST(int[] nums ,int left ,int right){
if(right - left < 0 ) return null;
int mid = (left + right) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums,left,mid-1);
root.right = sortedArrayToBST(nums,mid+1,right);
return root;
}
}
538. 把二叉搜索树转换为累加树
/**
* 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 sum = 0;
public TreeNode convertBST(TreeNode root) {
//测试用例中有root为空的树
if(root == null) return null;
if(root.right !=null){
convertBST(root.right);
}
//ERROR: 此处不能左孩子不能活得其父节点的值
// int increase = root.right == null ? 0 :root.right.val;
// root.val += increase;
sum += root.val;
root.val = sum ;
if(root.left != null){
convertBST(root.left);
}
return root;
}
}
更多推荐



所有评论(0)