Find Largest Value in Each Tree Row in C++


Suppose we have a binary tree, we have to find the largest elements of each level of that tree. So if the tree is like −


Then the output will be [3,5,8]

To solve this, we will follow these steps −

  • Define an array called ans

  • define a recursive function solve(), this will take tree node, and level, the level is initially 0. this method will act like −

  • if node is null, then return

  • if level = size of ans, then insert node value into ans, otherwise ans[level] := max of ans[level] and node value

  • call solve(left subtree of node, level + 1)

  • call solve(right subtree of node, level + 1)

  • From the main method, call the solve() using root as parameter, and level = 0

  • Then return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class TreeNode{
   public:
   int val;
   TreeNode *left, *right;
   TreeNode(int data){
      val = data;
      left = NULL;
      right = NULL;
   }
};
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
   q.push(*root);
   while(q.size()){
      TreeNode *temp = q.front();
      q.pop();
      if(!temp->left){
         if(val != NULL)
            temp->left = new TreeNode(val);
         else
            temp->left = new TreeNode(0);
         return;
      } else {
         q.push(temp->left);
      }
      if(!temp->right){
         if(val != NULL)
            temp->right = new TreeNode(val);
         else
            temp->right = new TreeNode(0);
         return;
      } else {
         q.push(temp->right);
      }
   }
}
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   }
   return root;
}
class Solution {
   public:
   vector <int> ans;
   void solve(TreeNode* node, int level = 0){
      if(!node)return;
      if(level == ans.size()){
         ans.push_back(node->val);
      } else {
         ans[level] = max(ans[level], node->val);
      }
      solve(node->left, level + 1);
      solve(node->right, level + 1);
   }
   vector<int> largestValues(TreeNode* root) {
      solve(root);
      return ans;
   }
};
main(){
   vector<int> v = {1,3,2,5,3,NULL,9};
   TreeNode *tree = make_tree(v);
   Solution ob;
   print_vector(ob.largestValues(tree));
}

Input

[1,3,2,5,3,null,9]

Output

[1, 3, 9, ]

Updated on: 30-Apr-2020

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements