Next larger
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.
The following line contains an integer, that denotes the value of n.
The first and only line of output contains data of the node, whose data is just greater than n.
Time Limit: 1 sec
10 3 20 30 40 2 40 50 0 0 0 0
18
20
10 3 20 30 40 2 40 50 0 0 0 0
21
30
/************************************************************ Following is the structure for the TreeNode class
template <typename T> class TreeNode { public: T data; vector<TreeNode<T>*> children; TreeNode(T data) { this->data = data; } ~TreeNode() { for (int i = 0; i < children.size(); i++) { delete children[i]; } } };
************************************************************/
TreeNode<int>* getNextLargerElement(TreeNode<int>* root, int x) { // Write your code here if(root == NULL){ return root; } TreeNode<int>* ans = NULL; if(root->data > x){ ans = root; } for(int i = 0; i<root->children.size(); i++){ TreeNode<int>* temp = getNextLargerElement(root->children[i], x); if(temp != NULL){ if(ans == NULL){ ans = temp; }else if(temp->data < ans->data){ ans = temp; } } } return ans; }
Comments
Post a Comment