Day20 二叉树 part06
我的思路:
类似从中序后序遍历的数组重建二叉树,只用对一个数组进行划分处理
解答:
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if(nums == null || nums.length == 0) {
return null;
}
return constructMBT(nums, 0, nums.length - 1);
}
public TreeNode constructMBT(int[] nums, int start, int end) {
if(start > end) {
return null;
}
int rootindex = findMaxValue(nums, start, end);
TreeNode root = new TreeNode(nums[rootindex]);
root.left = constructMBT(nums, start, rootindex - 1);
root.right = constructMBT(nums, rootindex + 1, end);
return root;
}
public int findMaxValue(int[] nums, int start, int end) {
int maxIndex = start;
for(int i = start; i <= end; i ++ ) {
if(nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
}
我的思路:
合并根节点,合并左子树和合并右子树,递归代码写出来很简单,但是如何递归还是要debug清楚
解答:
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null) {
return root2;
}
if(root2 == null) {
return root1;
}
TreeNode merge = new TreeNode(root1.val + root2.val);
merge.left = mergeTrees(root1.left, root2.left);
merge.right = mergeTrees(root1.right, root2.right);
return merge;
}
}
我的思路:
需要定义一个新结点(结点值和root相同),进行递归搜索,并且不断更新
解答:
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root == null) {
return null;
}
if(root.val == val) {
return root;
}
TreeNode res = new TreeNode(root.val);
if(root.val > val) {
res = searchBST(root.left, val);
}
if(root.val < val) {
res = searchBST(root.right, val);
}
return res;
}
}
我的思路:
用min和max限制范围,找到叶子结点(root == null)返回true
解答:
class Solution {
public boolean isValidBST(TreeNode root) {
return BTS(root, null, null);
}
public boolean BTS(TreeNode root, Integer min, Integer max) {
if(root == null) {
return true;
}
if((min != null && root.val <= min) || (max != null && root.val >= max)) {
return false;
}
return BTS(root.left, min, root.val) && BTS(root.right, root.val, max);
}
}