本文主要是介绍leetcode_1339. 分裂二叉树的最大乘积,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:1339. 分裂二叉树的最大乘积
DFS两次即可
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MOD ((int)pow(10, 9) + 7)static void post_order_traversal(struct TreeNode* node)
{if (!node) {return;}post_order_traversal(node->left);post_order_traversal(node->right);if (node->left) {node->val += node->left->val;}if (node->right) {node->val += node->right->val;}
}static void dfs(struct TreeNode* node, const long long sum, long long *ans)
{if (!node) {return;}long long a = node->val;long long b = sum - node->val;*ans = MAX(*ans, (a * b));dfs(node->left, sum, ans);dfs(node->right, sum, ans);
}int maxProduct(struct TreeNode* root){post_order_traversal(root);long long sum = root->val;long long ans = 0;dfs(root, sum, &ans);return (ans % MOD);
}
这篇关于leetcode_1339. 分裂二叉树的最大乘积的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!