LeetCode 515. Find Largest Value in Each Tree Row

来源:互联网 发布:js 点击显示modal 编辑:程序博客网 时间:2024/06/09 15:30

You need to find the largest value in each row of a binary tree.

Example:
Input:

      1     / \    3   2   / \   \    5   3   9 

Output: [1, 3, 9]

考察: 树的层序遍历/BFS

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> largestValues(TreeNode* root) {        vector<int> v;        deque<TreeNode*> dq;          if(root!=nullptr)            dq.push_back(root);        TreeNode* node = nullptr;        while(!dq.empty())        {            int sz = dq.size();     //  记录每行个数            int max = dq.front()->val;            for(int i=0;i<sz;++i)            {                node = dq.front();                max = max > node->val ? max :node->val;                dq.pop_front();                if(node->left)                    dq.push_back(node->left);                if(node->right)                    dq.push_back(node->right);            }            v.push_back(max);        }        return v;    }};