本文主要是介绍力扣算法学习day15-1,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
文章目录
力扣算法学习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;
}
}
已复习 24-两两交换链表中的结点
这篇关于力扣算法学习day15-1的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!