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 {
TreeNode pre;
public TreeNode trimBST(TreeNode root, int low, int high) {
if(root==null) return root;
if(root.val<low){
root=trimBST(root.right,low,high);
}else if(root.val>high){
root=trimBST(root.left,low,high);
}else{
root.left=trimBST(root.left,low,high);
root.right=trimBST(root.right,low,high);
}
return root;
}
}
108.将有序数组转换为二叉搜索树
思路
和之前根据前中后序遍历一样,划分数组构建树(在取中间节点的时候忘了加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 sortedArrayToBST(int[] nums) {
return createTree(nums,0,nums.length);
}
public TreeNode createTree(int[] nums,int left,int right){
if(left>=right) return null;
int mid=left+(right-left)/2;
TreeNode midNode=new TreeNode(nums[mid]);
midNode.left=createTree(nums,left,mid);
midNode.right=createTree(nums,mid+1,right);
return midNode;
}
}
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 count=0;
public TreeNode convertBST(TreeNode root) {
createNode(root);
return root;
}
public void createNode(TreeNode root){
if(root==null) return;
createNode(root.right);
root.val+=count;
count=root.val;
createNode(root.left);
return;
}
}