2017年5月4日 星期四

[LeetCode] 199. Binary Tree Right Side View

轉自LeetCode

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
You should return [1, 3, 4].
<Solution>
這題可以看做 Binary Tree Level Order Traversal 的衍生題

利用同樣思路解即可,主要變動的地方是
  • 每次 iteration,把 queue 裡面的最後一個 node,放到答案裡面
code 如下

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
if(!root) {
return ans;
}
queue<TreeNode *> nodeQue;
nodeQue.push(root);
while(!nodeQue.empty()) {
//>> put the right most node to ans
ans.push_back(nodeQue.back()->val);
//>> level order traversal
int len = nodeQue.size();
for(int i = 0; i < len; i++) {
TreeNode *tmpNode = nodeQue.front();
nodeQue.pop();
if(tmpNode->left) {
nodeQue.push(tmpNode->left);
}
if(tmpNode->right) {
nodeQue.push(tmpNode->right);
}
}
}
return ans;
}
};

沒有留言:

張貼留言