LeetCode Binary Tree Right Side View : 思想上的基于队列的广度优先遍历,形式上的一个简单变种
2015-04-07 10:30
555 查看
题目: 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
思路 : 分别用二个队列存储上一层元素,以及基于上一层元素获得的下一层元素,并取出其最后一个元素,以此类推
代码:
class Solution
{
public:
vector<int> rightSideView(TreeNode *root)
{
vector<int> result;
if(root == NULL)
{
return result;
}
//用二个vector交替存储上一行和下一行元素
queue<TreeNode*> top;
queue<TreeNode*> down;
top.push(root);
result.push_back(root->val);
while(!top.empty())
{
while(!top.empty())
{
TreeNode* node = top.front();
top.pop();
if(node->left)
{
down.push(node->left);
}
if(node->right)
{
down.push(node->right);
}
}
if(!down.empty())
{
TreeNode* rightMost = down.back();
result.push_back(rightMost->val);
}
while(!down.empty())
{
TreeNode* downNode = down.front();
top.push(downNode);
down.pop();
}
}
return result;
}
};
思路 : 分别用二个队列存储上一层元素,以及基于上一层元素获得的下一层元素,并取出其最后一个元素,以此类推
代码:
class Solution
{
public:
vector<int> rightSideView(TreeNode *root)
{
vector<int> result;
if(root == NULL)
{
return result;
}
//用二个vector交替存储上一行和下一行元素
queue<TreeNode*> top;
queue<TreeNode*> down;
top.push(root);
result.push_back(root->val);
while(!top.empty())
{
while(!top.empty())
{
TreeNode* node = top.front();
top.pop();
if(node->left)
{
down.push(node->left);
}
if(node->right)
{
down.push(node->right);
}
}
if(!down.empty())
{
TreeNode* rightMost = down.back();
result.push_back(rightMost->val);
}
while(!down.empty())
{
TreeNode* downNode = down.front();
top.push(downNode);
down.pop();
}
}
return result;
}
};
相关文章推荐
- 199.leetcode Binary Tree Right Side View(medium)[层次遍历二叉树 队列]
- LeetCode 199 Binary Tree Right Side View(二叉树层序遍历)
- leetcode---Binary Tree Right Side View---层次遍历
- leetcode_199题——Binary Tree Right Side View(广度优先搜索,队列queue)
- LeetCode—Binary Tree Right Side View 二叉树层序遍历变形,Flatten Binary Tree to Linked List前序遍历变形
- LeetCode Binary Tree Right Side View 树的层次遍历
- Leetcode 199 Binary Tree Right Side View
- [leetcode] 199 Binary Tree Right Side View
- [LeetCode 199] Binary Tree Right Side View
- LeetCode "Binary Tree Right Side View"
- [LeetCode]Binary Tree Right Side View
- Leetcode: Binary Tree Right Side View
- 199. Binary Tree Right Side View Leetcode Python
- leetCode 101/199-Symmetric Tree/Binary Tree Right Side View
- [leetcode] Binary Tree Right Side View
- Leetcode: Binary Tree Right Side View
- [Leetcode] Binary Tree Right Side View
- [leetcode]Binary Tree Right Side View
- LeetCode: Binary Tree Right Side View
- Leetcode Binary Tree Right Side View