给定二叉树中任意路径的最大乘积
给定一棵有N个节点的二叉树,任务是找到二叉树中任意路径的元素的最大乘积。
注意:路径从根开始,到树中的任何叶子结束。
例子:
Input:
4
/ \
2 8
/ \ / \
2 1 3 4
Output: 128
Explanation: Path in the given tree goes like {4, 8, 4} which gives the max score of 4 x 8 x 4 = 128.
Input:
10
/ \
7 5
\
1
Output: 70
Explanation: The path {10, 7} gives a score of 70 which is the maximum possible.
方法:解决问题的想法是通过使用递归的 DFS 遍历树。
For every node recursively find the maximum product of left subtree and right subtree of that node and return the product of that value with the node’s data.
按照下面提到的步骤解决问题
- 作为基本条件。如果根为 NULL,则只需返回 1。
- 调用左右子树的递归函数,得到两个子树的最大乘积。
- 返回当前节点的值乘以左右子树的最大积作为当前递归的答案。
下面是上述方法的实现。
C++
// C++ code for the above approach:
#include
using namespace std;
// Structure of a tree Node
struct Node {
int data;
Node* left;
Node* right;
Node(int val) { this->data = val; }
};
// Utility function to create a new Tree Node
long long findMaxScore(Node* root)
{
// Base Condition
if (root == 0)
return 1;
// Mmax product path = root->data
// multiplied by max of
// max_product_path of left subtree
// and max_product_path
// of right subtree
return root->data
* max(findMaxScore(root->left),
findMaxScore(root->right));
}
// Driver Code
int main()
{
Node* root = new Node(4);
root->left = new Node(2);
root->right = new Node(8);
root->left->left = new Node(3);
root->left->right = new Node(1);
root->right->left = new Node(3);
root->right->right = new Node(4);
// Function call
cout << findMaxScore(root) << endl;
return 0;
}
Java
// Java code for the above approach:
import java.util.*;
class GFG
{
// Structure of a tree Node
public static class Node {
int data;
Node left;
Node right;
Node(int val) { this.data = val; }
}
// Utility function to create a new Tree Node
public static long findMaxScore(Node root)
{
// Base Condition
if (root == null)
return 1;
// Mmax product path = root.data
// multiplied by max of
// max_product_path of left subtree
// and max_product_path
// of right subtree
return root.data
* Math.max(findMaxScore(root.left),
findMaxScore(root.right));
}
// Driver Code
public static void main(String[] args)
{
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(8);
root.left.left = new Node(3);
root.left.right = new Node(1);
root.right.left = new Node(3);
root.right.right = new Node(4);
// Function call
System.out.println(findMaxScore(root));
}
}
// This code is contributed by Taranpreet
Javascript
输出
128
时间复杂度: 在)。
辅助空间: O(树的高度)