二叉树 5
最大二叉树
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
- 创建一个根节点,其值为 nums 中的最大值。
- 递归地在最大值 左边 的 子数组前缀上 构建左子树。
- 递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
思路
同中序和后序遍历构造二叉树一样
class Solution {
Map<Integer,Integer> map = new HashMap<>();
public TreeNode constructMaximumBinaryTree(int[] nums) {
int max = 0;
for(int i = 0;i < nums.length;i++){
map.put(nums[i],i);
max = Math.max(max,nums[i]);
}
TreeNode root = new TreeNode(max);
root.left = buildTree(nums,0,map.get(max));
root.right = buildTree(nums,map.get(max) + 1,nums.length);
return root;
}
public TreeNode buildTree(int[] nums,int beg,int end){
if(beg >= end)
return null;
int max = 0;
for(int i = beg;i < end;i++){
max = Math.max(max,nums[i]);
}
int maxInd = map.get(max);
TreeNode root = new TreeNode(max);
root.left = buildTree(nums,beg,maxInd);
root.right = buildTree(nums,maxInd + 1,end);
return root;
}
}
合并二叉树
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 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.left = mergeTrees(root1.left,root2.left);
root1.right = mergeTrees(root1.right,root2.right);
return root1;
}
}
二叉搜索数中的搜索
给定二叉搜索树(BST)的根节点 root 和一个整数值 val。
你需要在 BST 中找到节点值等于 val 的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 null 。
思路
思路简单,只需在递归遍历二叉树的过程中,进行判断是否相等。
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root == null)
return null;
// if(root.val == val)
// return root;
if(root.val > val)
return searchBST(root.left,val);
if(root.val < val)
return searchBST(root.right,val);
return root;
}
}
验证二叉搜索数
给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
- 节点的左子树只包含 小于 当前节点的数。
- 节点的右子树只包含 大于 当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
思路
本体需要注意细节,不能单纯的比较左节点小于中间节点,右节点大于中间节点就完事了。
我们要比较的是 左子树所有节点小于中间节点,右子树所有节点大于中间节点。
class Solution {
// 注意细节,不是通过判断左节点的值小于根,右节点的值大于根
TreeNode max;
public boolean isValidBST(TreeNode root) {
if(root == null)
return true;
boolean left = isValidBST(root.left);
if(!left)
return false;
// 中序遍历,验证遍历的元素是不是从小到大
if(max != null && root.val <= max.val)
return false;
max = root;
boolean right = isValidBST(root.right);
return right;
}
}