669. 修剪二叉搜索树
题解及想法
使用中序递归法
当root的元素小于low的数值,那么应该递归右子树,并返回右子树符合条件的头结点。当root的元素大于high的,那么应该递归左子树,并返回左子树符合条件的头结点。接下来要将下一层处理完左子树的结果赋给root->left,处理完右子树的结果赋给root->right。最后返回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 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;
}
}
108.将有序数组转换为二叉搜索树
题解及想法
递归法,左闭右闭区间[left, right]。
/**
* 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 traversal(nums, 0, nums.length - 1);
}
private TreeNode traversal(int[] nums, int left, int right) {
if (left > right) return null;
int mid = left + ((right - left) >> 1);
TreeNode root = new TreeNode(nums[mid]);
root.left = traversal(nums, left, mid - 1);
root.right = traversal(nums, mid + 1, right);
return root;
}
}
538.把二叉搜索树转换为累加树
题解及想法
递归 右中左 根据二叉树搜索的特性,右中左就是从大到小遍历,通过pre指向遍历的节点的前一个,遍历到那个节点就加上pre,再把pre指向当前节点进行递归,就达到累加的目的。
/**
* 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) {
traversal(root);
return root;
}
//右中左
public void traversal(TreeNode root) {
if(root == null) return;
traversal(root.right); //右
root.val += pre; //加上前一个大节点的值 中
pre = root.val;
traversal(root.left); //左
}
}