DEV Community

Cover image for Find Largest Value in Each Tree Row
Ashis Chakraborty
Ashis Chakraborty

Posted on

Find Largest Value in Each Tree Row

Leetcode daily challenge: 25 Dec,2024.
Problem link

BFS is perfect when we are dealing specifically with rows/levels of a binary tree. With BFS, we handle one row of the tree at a time.

Here, we need to find the maximum value in each row. We can simply perform a BFS and for each row, keep track of the maximum value we have seen so far.

void bfs( TreeNode* node, vector<int>& result){

        queue<TreeNode *>Q;
        Q.push(node);

        int qSize = Q.size();
        int count =0;

        while(!Q.empty()){
            count = 0;
            priority_queue<int>heap;
            qSize = Q.size();

            while(count<qSize){// for each level/row find max value
                count++;
                TreeNode* temp = Q.front();
                Q.pop();
                heap.push(temp->val);

                if(temp->left != NULL)
                Q.push(temp->left);

                if(temp->right != NULL)
                Q.push(temp->right);

            }//while ends

            if(heap.size())
            result.push_back(heap.top());
        }
    }
    vector<int> largestValues(TreeNode* root) {
        if(root == NULL)
        return {};

        vector<int>result;
        bfs(root, result);///call bfs

        return result;
    }
Enter fullscreen mode Exit fullscreen mode

Video link with detailed explanation will be found here.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay