« Find Max Data Node in tree

Max data node

Given a generic tree, find and return the node with maximum data. You need to return the node which is having maximum data.

Return null if tree is empty.

Input format :

The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space.

Output Format :

The first and only line of output contains the data of the node with largest data in the given tree.

Constraints:

Time Limit: 1 sec

Sample Input 1:

10 3 20 30 40 2 40 50 0 0 0 0

Sample Output 1:

50

1#include <iostream>
2#include <queue>
3#include <vector>
4using namespace std;
5
6template <typename T>
7class TreeNode {
8 public:
9 T data;
10 vector<TreeNode<T>*> children;
11
12 TreeNode(T data) { this->data = data; }
13
14 ~TreeNode() {
15 for (int i = 0; i < children.size(); i++) {
16 delete children[i];
17 }
18 }
19};
20
21TreeNode<int>* maxDataNode(TreeNode<int>* root) {
22 // Write your code here
23 if(root == NULL){
24 return NULL;
25 }
26 TreeNode<int>* maxNode = root;
27 for(int i=0; i<root->children.size(); i++){
28 TreeNode<int>* currMax = maxDataNode(root->children[i]);
29 if(currMax != NULL && maxNode->data < currMax->data){
30 maxNode = currMax;
31 }
32 }
33 return maxNode;
34}
35
36TreeNode<int>* takeInputLevelWise() {
37 int rootData;
38 cin >> rootData;
39 TreeNode<int>* root = new TreeNode<int>(rootData);
40
41 queue<TreeNode<int>*> pendingNodes;
42
43 pendingNodes.push(root);
44 while (pendingNodes.size() != 0) {
45 TreeNode<int>* front = pendingNodes.front();
46 pendingNodes.pop();
47 int numChild;
48 cin >> numChild;
49 for (int i = 0; i < numChild; i++) {
50 int childData;
51 cin >> childData;
52 TreeNode<int>* child = new TreeNode<int>(childData);
53 front->children.push_back(child);
54 pendingNodes.push(child);
55 }
56 }
57
58 return root;
59}
60
61int main() {
62 TreeNode<int>* root = takeInputLevelWise();
63 TreeNode<int>* ans = maxDataNode(root);
64
65 if (root != NULL) {
66 cout << ans->data;
67 }
68}