515. Find Largest Value in Each Tree Row

代码有点渣,效率不够高,简单的层次优先遍历,注意各种情况。。。。比如[],[-12,1,1],[1,-12,0]blablabla题目并没有说不能是负数,注意审题,好好考虑极端情况。

自己的代码

/**
 * 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 largestValues(TreeNode* root) {
        vector output;
        queue bfs;
        queue depth;
        int now = 1, max = 0;
        if (root != NULL){
            bfs.push(root);
            depth.push(1);
            max = root -> val;
            while (bfs.size()){
                if (depth.front() != now){
                    output.push_back(max);
                    max = bfs.front() -> val;
                    now += 1;
                }
            max = max >= bfs.front() -> val ? max : bfs.front()->val;
            if (bfs.front() -> left != NULL){
                bfs.push(bfs.front() -> left);
                depth.push(now + 1);
            }
            if (bfs.front() -> right != NULL){
                bfs.push(bfs.front() -> right);
                depth.push(now + 1);
            }
            bfs.pop();
            depth.pop();
        }
        output.push_back(max);
        }
        return output;
    }
};

你可能感兴趣的:(515. Find Largest Value in Each Tree Row)