二叉树层序遍历应用之Binary Tree Right Side View
2015-05-07 17:22
411 查看
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,
You should return
Solutions:
易想到求的是每层中最右的一个节点。
二叉树层序遍历过程中,每次循环开始时,队列中存放的刚好是将要访问的一层的节点。
/**
* 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> result;
if(root==NULL){
return result;
}
queue<TreeNode*> Q;
Q.push(root);
TreeNode *right;
while(!Q.empty()) {
int Qsize=Q.size();
for(int i=0; i<Qsize; ++i) {
right=Q.front();
Q.pop();
if(right->left != NULL){
Q.push(right->left);
}
if(right->right != NULL){
Q.push(right->right);
}
}
result.push_back(right->val);
}
}
};
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return
[1, 3, 4].
Solutions:
易想到求的是每层中最右的一个节点。
二叉树层序遍历过程中,每次循环开始时,队列中存放的刚好是将要访问的一层的节点。
/**
* 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> result;
if(root==NULL){
return result;
}
queue<TreeNode*> Q;
Q.push(root);
TreeNode *right;
while(!Q.empty()) {
int Qsize=Q.size();
for(int i=0; i<Qsize; ++i) {
right=Q.front();
Q.pop();
if(right->left != NULL){
Q.push(right->left);
}
if(right->right != NULL){
Q.push(right->right);
}
}
result.push_back(right->val);
}
}
};
相关文章推荐
- LeetCode—Binary Tree Right Side View 二叉树层序遍历变形,Flatten Binary Tree to Linked List前序遍历变形
- LeetCode 199 Binary Tree Right Side View(二叉树层序遍历)
- 199.leetcode Binary Tree Right Side View(medium)[层次遍历二叉树 队列]
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- [LeetCode] Binary Tree Right Side View 二叉树的右侧视图
- Binary Tree Right Side View:查找二叉树最右支
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- LeetCode Binary Tree Right Side View : 思想上的基于队列的广度优先遍历,形式上的一个简单变种
- [leetcode]Minimum Depth of Binary Tree--二叉树层序遍历的应用
- leetcode---Binary Tree Right Side View---层次遍历
- Binary Tree Right Side View 二叉树:右视图
- LeetCode Binary Tree Right Side View 树的层次遍历
- LeetCode OJ:Binary Tree Right Side View(右侧视角下的二叉树)
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- Binary Tree Right Side View 从左边视角输出二叉树的值
- [leetcode]Minimum Depth of Binary Tree--二叉树层序遍历的应用
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- LeetCode 199 Binary Tree Right Side View
- Binary Tree Level Order Traversal,层序遍历二叉树,每层作为list,最后返回List<list>
- Leetcode162: Binary Tree Right Side View