力扣算法学习day15-1
654-最大二叉树
题目
代码实现
/**
* 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 constructMaximumBinaryTree(int[] nums) {
return treeBuild(0,nums.length-1,nums);
}
public TreeNode treeBuild(int left,int right,int[] nums){
// 终止条件
if(left > right){
return null;
}
if(left == right){// 可以不加这个,加上速度更快,2ms->1ms
return new TreeNode(nums[left]);
}
// 寻找最大值,并记录最大值的坐标。
int max = nums[left];
int maxIndex = left;
for(int i = left;i <= right;i++){
if(max < nums[i]){
max = nums[i];
maxIndex = i;
}
}
// 找到根结点
TreeNode root = new TreeNode(max);
// 递归左区间和右区间
TreeNode leftNode = treeBuild(left,maxIndex-1,nums);
TreeNode rightNode = treeBuild(maxIndex+1,right,nums);
// 连接左右结点
root.left = leftNode;
root.right = rightNode;
return root;
}
}
617-合并二叉树
题目
代码实现
/**
* 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 mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null && root2 != null){
return root2;
} else if(root2 == null && root1 != null){
return root1;
} else if(root1 == null && root2 == null){
return null;
}
root1.val = root1.val + root2.val;
root1.left = mergeTrees(root1.left,root2.left);
root1.right = mergeTrees(root1.right,root2.right);
return root1;
}
}