LeetCode OJ 515. Find Largest Value in Each Tree Row

LeetCode OJ 515. Find Largest Value in Each Tree Row


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]

解題思路

用隊列queue實現廣度優先搜索,將A層的數存到隊列中,並且在A+1層數字入隊的過程中進行A層的比較。當A+1的數存完之後,也就比較完了A層每一個數從而得到A層最大的數,並存到結果的vector中。對這棵二叉樹的每一層都進行這樣的操作,到了最後一層也就得到輸出結果。

Note:
把A+1層的數字存到隊列的操作是這樣實現的:
首先讀取當前隊列q的size存到count(這是A層的數的數量),當count不爲0的時候,我們將提取隊列的隊首元素front(),將它的左右子節點(如果不爲空)存到q的隊尾,並且q的隊首出隊(q.pop()),count自減1;如果count爲0,就說明A+1層的數字已經全部存到了隊列中並且A層的每一個數字已經進行了比較。

代碼

個人github代碼鏈接


/**
 * 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> ans;
        if(!root)    return ans;
        queue<TreeNode*> q;
        q.push(root);
        //ans.push_back(root->val);
        int count, num;
        TreeNode* node;
        while(!q.empty()){
            num = INT_MIN;
            count = q.size();
            while(count){
                node = q.front();
                if(num < node->val)
                    num = node->val;
                if(node->left)    q.push(node->left);
                if(node->right)    q.push(node->right);
                q.pop();
                count --;
            }
            ans.push_back(num);
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章