原題
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,該vector內的節點即為下一層的所有節點。
代碼
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> result;
vector<TreeNode*> save1, save2;
if (root == NULL) {
return result;
}
save1.push_back(root);
while (save1.size() > 0) {
int max = save1[0]->val;
for (int i = 0; i < save1.size(); i++) {
if (max < save1[i]->val) {
max = save1[i]->val;
}
if (save1[i]->left != NULL){
save2.push_back(save1[i]->left);
}
if (save1[i]->right != NULL){
save2.push_back(save1[i]->right);
}
}
save1 = save2;
save2.clear();
result.push_back(max);
}
return result;
}
};
感想
忘記了驗證傳入的根節點是否為空,就這樣又被坑了、、、