美文网首页
Leetcode-Find Largest Value in E

Leetcode-Find Largest Value in E

作者: Juliiii | 来源:发表于2017-11-24 19:17 被阅读0次

Description

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]

Explain

这题题意一眼就知道要干嘛,言简意赅。就是要找树的每一层的最大值。这里在leetcode的分类是DFS。然后我觉得这题用BFS来做更好做一点,也更好理解一点。我们只要遍历每一层的节点,然后比较得出最大值,然后插入vector即可。下面上代码

Code

/**
 * 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> res;
        if (!root) return res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()) {
            int len = q.size();
            int max = INT_MIN;
            for (int i = 0; i < len; i++) {
                TreeNode* cur = q.front();
                q.pop();
                if (cur->val > max) max = cur->val;
                if (cur->left) q.push(cur->left);
                if (cur->right) q.push(cur->right);
            }
            res.push_back(max);
        }
        return res;
    }
};

相关文章

网友评论

      本文标题:Leetcode-Find Largest Value in E

      本文链接:https://www.haomeiwen.com/subject/zpifbxtx.html