美文网首页
515. Find Largest Value in Each

515. Find Largest Value in Each

作者: 殷水臣 | 来源:发表于2017-02-21 00:00 被阅读0次

代码有点渣,效率不够高,简单的层次优先遍历,注意各种情况。。。。比如[],[-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<int> largestValues(TreeNode* root) {
        vector<int> output;
        queue<TreeNode *> bfs;
        queue<int> 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

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