提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
二叉树的递归分为「遍历」和「分解问题」两种思维模式,这道题需要用到「分解问题」的思维,而且要用到后序位置的妙用。
一、力扣1339. 分裂二叉树的最大乘积
/**
* 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 {
HashSet<Long> set = new HashSet<>();
public int maxProduct(TreeNode root) {
long sum = fun(root);
double res = 0;
double t = 1e9 + 7;
for(long s : set){
double temp = s * (sum - s);
res = Math.max(res,temp);
}
return (int)(res%t);
}
public long fun(TreeNode root){
if(root == null){
return 0;
}
long left = fun(root.left);
long right = fun(root.right);
long cur = left + right + root.val;
set.add(cur);
return cur;
}
}
二、力扣2049. 统计最高分的节点数目
class Solution {
int[][] tree;
HashMap<Long,Integer> scoreToCount = new HashMap<>();
public int countHighestScoreNodes(int[] parents) {
this.tree = buildTree(parents);
countNode(0);
long maxScore = 0;
for(long score : scoreToCount.keySet()){
maxScore = Math.max(maxScore,score);
}
return scoreToCount.get(maxScore);
}
int countNode(int root){
if(root == -1){
return 0;
}
int n = tree.length;
int leftCount = countNode(tree[root][0]);
int rightCount = countNode(tree[root][1]);
int otherCount = n - leftCount - rightCount -1;
long score = (long)Math.max(leftCount,1) * Math.max(rightCount,1) * Math.max(otherCount,1);
scoreToCount.put(score,scoreToCount.getOrDefault(score,0)+1);
return leftCount + rightCount + 1;
}
public int[][] buildTree(int[] parents){
int n = parents.length;
int[][] tree = new int[n][2];
for(int i = 0; i < n ; i ++){
tree[i][0] = tree[i][1] = -1;
}
for(int i = 1; i < n ; i ++){
int parent_i = parents[i];
if(tree[parent_i][0] == -1){
tree[parent_i][0] = i;
}else{
tree[parent_i][1] = i;
}
}
return tree;
}
}
三、力扣1372. 二叉树中的最长交错路径
/**
* 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 {
int res = 0;
public int longestZigZag(TreeNode root) {
fun(root);
return res;
}
public int[] fun(TreeNode root){
if(root == null){
return new int[]{-1,-1};
}
int[] left = fun(root.left);
int[] right = fun(root.right);
int p1 = left[1] + 1;
int p2 = right[0] + 1;
res = Math.max(res,Math.max(p1,p2));
return new int[]{p1,p2};
}
}
本文介绍了如何使用递归的分解问题思维解决力扣平台上的三个二叉树相关问题:1339分裂二叉树的最大乘积,2049统计最高分节点数目,以及1372二叉树中的最长交错路径。作者详细解释了算法和代码实现。
401

被折叠的 条评论
为什么被折叠?



