« 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;56template <typename T>7class TreeNode {8 public:9 T data;10 vector<TreeNode<T>*> children;1112 TreeNode(T data) { this->data = data; }1314 ~TreeNode() {15 for (int i = 0; i < children.size(); i++) {16 delete children[i];17 }18 }19};2021TreeNode<int>* maxDataNode(TreeNode<int>* root) {22 // Write your code here23 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}3536TreeNode<int>* takeInputLevelWise() {37 int rootData;38 cin >> rootData;39 TreeNode<int>* root = new TreeNode<int>(rootData);4041 queue<TreeNode<int>*> pendingNodes;4243 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 }5758 return root;59}6061int main() {62 TreeNode<int>* root = takeInputLevelWise();63 TreeNode<int>* ans = maxDataNode(root);6465 if (root != NULL) {66 cout << ans->data;67 }68}