654.最大二叉树
题目链接:https://leetcode.cn/problems/maximum-binary-tree/submissions/
题目要求:
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
创建一个根节点,其值为 nums 中的最大值。
递归地在最大值 左边 的 子数组前缀上 构建左子树。
递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
🤔解题思路
💻前序遍历
/**
* 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 make(nums,0,nums.length - 1);
}
public TreeNode make(int[] nums,int left,int right){
//只有一个元素,说明遍历到叶子节点,直接返回该节点
if(left == right) return new TreeNode(nums[left]);
//遍历数组,找到最大值,构造根节点
int index = 0;
int max = 0;
for(int i = left;i <= right;i++){
if(max <= nums[i]){
max = nums[i];
index = i;
}
}
TreeNode root = new TreeNode(max);
//根据最大值索引构造左子树和右子树
if(index - left > 0){
root.left = make(nums,left,index - 1);
}
if(right - index > 0){
root.right = make(nums,index + 1,right);
}
return root;
}
}
617.合并二叉树
题目链接:https://leetcode.cn/problems/merge-two-binary-trees/
题目要求:
给你两棵二叉树: root1 和 root2 。
想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。
返回合并后的二叉树。
注意: 合并过程必须从两个树的根节点开始。
🤔解题思路
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
//递归终止条件
if(root1 == null) return root2;
if(root2 == null) return root1;
//合并节点
root1.val += root2.val;
//修改root1的结构,不直接创建新的二叉树
//递归合并左右子树
root1.left = mergeTrees(root1.left,root2.left);
root1.right = mergeTrees(root1.right,root2.right);
return root1;
}
}
700.二叉搜索树中的搜索
题目链接:https://leetcode.cn/problems/search-in-a-binary-search-tree/submissions/
题目要求:
给定二叉搜索树(BST)的根节点 root 和一个整数值 val。
你需要在 BST 中找到节点值等于 val 的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 null 。
🤔解题思路
利用二叉搜索树的特性,左节点小于根节点,右节点大于根节点;来确定搜索的方向
//迭代法
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while(root != null){
if(root.val > val){
root = root.left;
}else if(root.val < val){
root = root.right;
}else{
return root;
}
}
return null;
}
}
//递归法
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root == null || root.val == val) return root;
if(root.val > val) return searchBST(root.left,val);
if(root.val < val) return searchBST(root.right,val);
return null;
}
}
98.验证二叉搜索树
题目链接:力扣
题目要求:
给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
🤔解题思路
中序遍历:看到二叉搜索树就要想到中序遍历,利用二叉搜索树的特性,中序遍历的二叉搜索树是递增的
class Solution {
//用于记录前一节点
TreeNode pre = null;
public boolean isValidBST(TreeNode root) {
if(root == null) return true;
boolean left = isValidBST(root.left);
//如果前一个节点大于当前节点,则不是二叉搜索树
if(pre != null && pre.val >= root.val) return false;
//更改节点的值
pre = root;
boolean right = isValidBST(root.right);
return left && right;
}
}