Leetcode 刷题Day19休息&Day20--------------------二叉树
1. 654.最大二叉树
- 题目链接:https://leetcode.cn/problems/maximum-binary-tree/
- 文章讲解:https://programmercarl.com/0654.%E6%9C%80%E5%A4%A7%E4%BA%8C%E5%8F%89%E6%A0%91.html
- 视频讲解:https://www.bilibili.com/video/BV1MG411G7ox
方法:左闭右闭(左边和右边的值都被计算的) && 前序遍历
步骤:
- 先重新定义一个参数列表还要含有左边index和右边index的方法
- 分为三种情况:没有元素(return null),有一个元素(return 以这个值为val的node),有超过一个元素(找出最大的value,和对应的index,以此为界限,分别在左右两边继续递归调用该方法)
- 返回根节点
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructMaximumBinaryTree1(nums, 0, nums.length-1);
}
public TreeNode constructMaximumBinaryTree1(int[] nums, int leftIndex, int rightIndex) {
if (rightIndex < leftIndex) {// 没有元素了
return null;
}
if (rightIndex == leftIndex) {// 只有一个元素
return new TreeNode(nums[leftIndex]);
}
int maxIndex = leftIndex;// 最大值所在位置
int maxVal = nums[maxIndex];// 最大值
for (int i = leftIndex + 1; i <= rightIndex; i++) {
if (nums[i] > maxVal){
maxVal = nums[i];
maxIndex = i;
}
}
TreeNode root = new TreeNode(maxVal);
// 根据maxIndex划分左右子树
root.left = constructMaximumBinaryTree1(nums, leftIndex, maxIndex-1);
root.right = constructMaximumBinaryTree1(nums, maxIndex + 1, rightIndex);
return root;
}
}
2. 617.合并二叉树
- 题目链接:https://leetcode.cn/problems/merge-two-binary-trees/
- 文章讲解:https://programmercarl.com/0617.%E5%90%88%E5%B9%B6%E4%BA%8C%E5%8F%89%E6%A0%91.html
- 视频讲解:https://www.bilibili.com/video/BV1m14y1Y7JK
前序遍历:
步骤:
- 判断哪个树为空,直接返回另一个树
- 在root1 的基础上进行值的想加,left左节点的遍历,right右节点的遍历
- 返回root1
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1==null) return root2;
if(root2==null) return root1;
root1.val+=root2.val;
root1.left=mergeTrees(root1.left,root2.left);
root1.right=mergeTrees(root1.right,root2.right);
return root1;
}
}
3. 700.二叉搜索树中的搜索
- 题目链接:https://leetcode.cn/problems/search-in-a-binary-search-tree/
- 文章讲解: https://programmercarl.com/0700.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E6%90%9C%E7%B4%A2.html
- 视频讲解:https://www.bilibili.com/video/BV1wG411g7sF
步骤:
- 先判断根是否为空或者根节点的值是否就是所要找的值
- 先找左边,如果左边能找到(结果不为空),那就返回左边的值;如果左边没找到结果,那就相同的方法找右边
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root==null||root.val==val) return root;
TreeNode left=searchBST(root.left,val);
if(left!=null) return left;
else return searchBST(root.right,val);
}
}
4. 98.验证二叉搜索树
- 题目链接:https://leetcode.cn/problems/validate-binary-search-tree/
- 文章讲解:https://programmercarl.com/0098.%E9%AA%8C%E8%AF%81%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html
- 视频讲解:https://www.bilibili.com/video/BV18P411n7Q4