Without recursion,Simple level order traversal approach


#1

int Solution::solve(TreeNode* A) {
if(A==NULL) {
return 0;
}
vector ans; // This vector will stores the all levels sum
queue<TreeNode*> q;
q.push(A);
q.push(NULL);
int temp=0;

// Level order traversal 
while(!q.empty()) {
    TreeNode* curr=q.front();
    q.pop();
    
    if(curr!=NULL) {
        temp+=curr->val;
    }
    
    if(curr==NULL) {
        ans.push_back(temp);     // means one level is completed,so push the sum into ans vector.
        temp=0;
        if(q.empty()) {
            break;
        }
        q.push(NULL);
        continue;
    }
    else {
        if(curr->left!=NULL) {
            q.push(curr->left);
        }
        if(curr->right!=NULL) {
            q.push(curr->right);
        }
    }
}

sort(ans.begin(),ans.end());     // sort the ans vector and return the last element .
return ans[ans.size()-1];

}