Given a tree with the weights of all the nodes, the task is to find the maximum weighing node whose weight has even digit sum.
Input: Tree = 5 / \ 10 6 / \ 11 8 Output: 11 Explanation: The tree node weights are: 5 -> 5 10 -> 1 + 0 = 1 6 -> 6 11 -> 1 + 1 = 2 8 -> 8 Here, digit sum for nodes containing 10, 6 and 8 are even. Hence, the maximum weighing even digit sum node is 11. Input: Tree = 1 / \ 4 7 / \ / \ 11 3 15 8 Output: 15 Explanation: Here, digit sum for nodes containing 4, 11, 15 and 8 are even. Hence, the maximum weighing even digit sum node is 15.
Approach: To solve the problem mentioned above follow the steps given below:
- The idea is to perform a depth first search on the tree and for every node.
- First find the digit sum for the weight present in the node by iterating through each digit and then check if the node has even digit sum or not.
- Finally, if it has even digit sum then check if this node is the maximum even digit sum node we have found so far, if yes, then make this node the maximum even digit sum node.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space complexity: O(1)
- Find the maximum node at a given level in a binary tree
- Find the node with maximum value in a Binary Search Tree
- Find the node with maximum value in a Binary Search Tree using recursion
- Find farthest node from each node in Tree
- Node having maximum sum of immediate children and itself in n-ary tree
- Get maximum left node in binary tree
- Maximum XOR with given value in the path from root to given node in the tree
- Maximum difference between node and its ancestor in Binary Tree
- Minimum valued node having maximum depth in an N-ary Tree
- Iterative Segment Tree (Range Maximum Query with Node Update)
- Range Queries to find the Element having Maximum Digit Sum
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Find the node whose xor with x gives maximum value
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Find root of the tree where children id sum for every node is given
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : stutipathak31jan