![]() |
VOOZH | about |
Given a binary tree, the task is to find the node whose children have maximum Sibling product in the given Binary Tree. If there are multiple such nodes, return the node which has the maximum value.
Examples:
Input: Tree:
4
/ \
5 2
/ \
3 1
/ \
6 12
Output: 3
Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 and 12 which are the children of node 3.Input: Tree:
1
/ \
3 5
/ \ / \
6 9 4 8
Output: 3
Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 and 9 which are the children of node 3.
To solve this problem, level order traversal of the Binary Tree can be used to find the maximum sum of siblings. Follow the following steps:
Below is the implementation of the above approach:
3
Time Complexity: O(V) where V is the number of nodes in the tree.
Auxiliary Space: O(V).
- The idea is to traverse the tree in postorder fashion .
- Recursively , call the left subtree.
- Recursively , call the right subtree.
- Get , the product of left child and right child and update the max variable and max parent variable with parent root of left and right child.
- Here , max parent variable will be storing the parent node of the maximum product siblings.
Below is the Implementation of this Approach :-
3
Time Complexity: O(N) , where N is the number of nodes in the tree
Auxiliary Space : O(N) , recursion stack space