[LeetCode][Medium] 199. Binary Tree Right Side View
Leetcode 網址: https://leetcode.com/problems/binary-tree-right-side-view/
題目說明:
給定一個 Binary Tree,請由 Top 至 Bottom 出每一層中最右邊 Node 的值。
解題說明:
題目很清楚,就是一題 Level Order Traversal 的題目,所以直接用 queue 處理即可。
程式碼
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
queue<TreeNode*> q;
if (root) q.push(root);
while (q.size() > 0) {
TreeNode* rightNode = NULL;
for (int i = 0, size = q.size(); i < size; i++, q.pop()) {
rightNode = q.front();
if (rightNode->left) q.push(rightNode->left);
if (rightNode->right) q.push(rightNode->right);
}
if (rightNode) ans.push_back(rightNode->val);
}
return ans;
}
};
結果
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Binary Tree Right Side View.
Memory Usage: 11.8 MB, less than 29.31% of C++ online submissions for Binary Tree Right Side View.
留言
張貼留言