[leetcode]515. Find Largest Value in Each Tree Row

[leetcode]515. Find Largest Value in Each Tree Row


Analysis

啊啊啊啊啊啊—— [生死有命富貴在天]

You need to find the largest value in each row of a binary tree.
層序遍歷,然後找到每一層的最大值就行了~

Implement

方法一(層序遍歷)

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

方法二(DFS,好像會快一點,但是我也不知道爲啥。。。)

/**
 * 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> maxs;
        find(root, 0, maxs);
        return maxs;
    }

private:
    void find(TreeNode* node, int row, vector<int>& maxs) {
        if (!node) {
            return;
        }

        if (row >= maxs.size()) {
            maxs.push_back(node->val);
        }
        else {
            maxs[row] = max(maxs[row], node->val);
        }

        find(node->left, row + 1, maxs);
        find(node->right, row + 1, maxs);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章