We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
//Maximum Level Sum in a Binary Tree#include<iostream>#include<queue>usingnamespacestd;structNode{intval;Node*left,*right;Node(intx):val(x),left(nullptr),right(nullptr){}};intmaxLevelSum(Node*root){if(!root)return0;queue<Node*>q;q.push(root);intmaxSum=root->val;while(!q.empty()){intlevelSum=0,size=q.size();for(inti=0;i<size;i++){Node*node=q.front();q.pop();levelSum+=node->val;if(node->left)q.push(node->left);if(node->right)q.push(node->right);}maxSum=max(maxSum,levelSum);}returnmaxSum;}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(8);cout<<maxLevelSum(root);return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
"Hello World!" in C
You are viewing a single comment's thread. Return to all comments →