669. 修剪二叉搜索树
递归法:
终止条件:
if(root == null) return root;
如果root(当前节点)的元素小于low的数值,那么应该递归右子树,并返回右子树符合条件的头结点。
如果root(当前节点)的元素大于high的,那么应该递归左子树,并返回左子树符合条件的头结点。
接下来要将下一层处理完左子树的结果赋给root->left,处理完右子树的结果赋给root->right。
root.left = trimBST(root.left,low,high);
root.right = trimBST(root.right,low,high);
return root;
返回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 root;
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;
}
}
/**
* 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 root;
root.left = trimBST(root.left,low,high);
if(root.val < low){
return trimBST(root.right,low,high);
}
root.right = trimBST(root.right,low,high);
if(root.val > high){
return trimBST(root.left,low,high);
}
return root;
}
}
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 f(nums,0,nums.length - 1);
}
TreeNode f(int[] nums, int left, int right){
if(left > right) return null;
int mid = left + (right - left)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = f(nums,left,mid - 1);
root.right = f(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) {
f(root);
return root;
}
void f(TreeNode root){
if(root == null) return;
f(root.right);
sum += root.val;
root.val = sum;
f(root.left);
}
}