515. Find Largest Value in Each Tree Row(Tree)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyuanzong/article/details/85124612

链接:https://leetcode.com/problems/find-largest-value-in-each-tree-row/

题目:求二叉树每一层的最大值;

思路:采用层次遍历方式。

代码:

class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
                vector<int>ret;
                if(!root) return ret;
        
                queue<TreeNode*>Q;
                Q.push(root);
                int curlow = 1;
                int nextlow = 0;
                int maxval = 0;
                bool newlow = 1;
        
                while(!Q.empty()){
                      TreeNode *t = Q.front();
                    
                      if(!newlow){
                           maxval = max(maxval,t->val);
                      }
                      else {
                          maxval = t->val;
                          newlow = 0;
                      }
                    
                      if(t->left) {
                          Q.push(t->left);
                          nextlow++;
                      }
                    
                      if(t->right){
                          Q.push(t->right);
                          nextlow++;
                      }
                    
                      curlow--;
                      if(curlow==0){
                          curlow = nextlow;
                          nextlow = 0;
                          ret.push_back(maxval);
                          newlow = 1;
                      }
                    
                      Q.pop();
                }
        
               return ret;
         
    }
};

猜你喜欢

转载自blog.csdn.net/tangyuanzong/article/details/85124612