669. 修剪二叉搜索树
思路: 这道题和删除节点异曲同工。不过要注意避坑:当遍历到不在范围内的节点时,不要直接返回null或直接返回其左或右孩子,而是继续对其左或右孩子做递归。
/*** 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) {return dfs(root,low,high);} public TreeNode dfs(TreeNode root, int low, int high){if(root==null) return null;if(root.val<low) return dfs(root.right,low,high);//注意,不要直接返回root.rightif(root.val>high) return dfs(root.left,low,high);root.left=dfs(root.left,low,high);root.right=dfs(root.right,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 getSortedArrayToBST(nums,0,nums.length-1);}public TreeNode getSortedArrayToBST(int[] nums,int left,int right){if(left>right) return null;if(left==right) return new TreeNode(nums[left]);int mid=left+(right-left)/2;TreeNode root=new TreeNode(nums[mid]);root.left=getSortedArrayToBST(nums,left,mid-1);root.right=getSortedArrayToBST(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 {TreeNode pre;public TreeNode convertBST(TreeNode root) {getConvertBST(root);return root;}public void getConvertBST(TreeNode node){if(node==null) return;getConvertBST(node.right);if(pre!=null){node.val=node.val+pre.val;}pre=node;getConvertBST(node.left);}
}