我新建的个人博客,欢迎访问:hmilzy.github.io
669. 修剪二叉搜索树
题目链接: 修剪二叉搜索树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class Solution { public TreeNode trimBST(TreeNode root, int low, int high) { if(root == null) { return null; } if(root.val < low) { TreeNode right = trimBST(root.right,low,high); return right; } if(root.val > high) { TreeNode left = trimBST(root.left,low,high); return left; } root.left = trimBST(root.left,low,high); root.right = trimBST(root.right,low,high); return root; } }
|
108.将有序数组转换为二叉搜索树
题目链接: 将有序数组转换为二叉搜索树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
class Solution { public TreeNode sortedArrayToBST(int[] nums) { return traversal(nums,0,nums.length - 1); } public TreeNode traversal(int[] nums,int left,int right) { if(left > right) { return null; }
TreeNode root = new TreeNode(); int middle = left + (right - left) / 2; root.val = nums[middle];
root.left = traversal(nums,left,middle - 1); root.right = traversal(nums,middle + 1,right);
return root; } }
|
538.把二叉搜索树转换为累加树
题目链接: 把二叉搜索树转换为累加树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class Solution { int pre; public TreeNode convertBST(TreeNode root) { pre = 0; 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); } }
|