[leetcode-515-Find Largest Value in Each Tree Row]
阿新 • • 發佈:2017-05-24
ron 遍歷 vector div spa cto int ges pop
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]
思路:
層次遍歷,每一層選出當前層最大值。
vector<int> largestValues(TreeNode* root) { vector<int>result; if (root == NULL)return result; queue<TreeNode*>que; que.push(root); int tempmax = INT_MIN; while (!que.empty()) { int levelsize = que.size(); TreeNode* temp; for (int i = 0; i < levelsize;i++) { temp = que.front(); que.pop();if (temp->left != NULL)que.push(temp->left); if (temp->right != NULL)que.push(temp->right); tempmax = max(tempmax, temp->val); } result.push_back(tempmax); tempmax = INT_MIN; } return result; }
[leetcode-515-Find Largest Value in Each Tree Row]