515. Find Largest Value in Each Tree Row(Tree)
阿新 • • 發佈:2019-01-01
連結: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; } };