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]
The meaning of the title: Find the maximum value of each line.
Solution ideas: 1. Put the nodes of the current line in an array, and then put all the nodes of the next line of the current line in In another array, this can traverse the nodes of each row.
2. When the nodes of the current row are traversed, find the maximum value of each row.
3. The termination condition is that the number of nodes in the current row is 0.
Notes:
1 .root node may be null
1 #include<queue> 2 #include<algorithm> 3 class Solution { 4 5 public : 6 static bool cmp(TreeNode* a, TreeNode* b){ 7 return a->val > b-> val; 8 } // Sort in ascending order according to the value of val 9 vector< int > largestValues(TreeNode* root) { 10 // p is used to save the node of the current row 11 vector<TreeNode*> p; 12 p.push_back(root); 13 // put Enter the val of the root node, when the root node is null, do not put 14 vector< int > ans; 15 if (root) ans.push_back(root-> val); 16 // Infinite loop. Exit when the next line of the current line is all null 17 while ( true ){ 18 vector<TreeNode*> q; 19 int len = p.size(); 20 // The next node of all nodes in the current line 21 while (len){ 22 TreeNode* temp = p[len- 1 ]; 23 if ( temp == NULL) break ; 24 len-- ; 25 if(temp->left) q.push_back(temp->left); 26 if(temp->right) q.push_back(temp->right); 27 } 28 p = q; 29 sort(q.begin(), q.end(), cmp); 30 if(p.empty()) break; 31 ans.push_back(q[0]->val); 32 } 33 return ans; 34 } 35 };