您的位置:首页 > 其它

LeetCode 199 Binary Tree Right Side View(二叉树层序遍历)

2017-07-14 22:41 453 查看
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]
.

题目大意:给出一棵二叉树,假设你现在站在它的右侧,输出你看到的节点(即二叉树的右视图)。

解题思路:二叉树层序遍历,输出每一层的最后一个节点即可。因为层序遍历有递归和非递归两种写法,所以本题也给出了两种解法。

代码如下:

/**
* 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) {
// levelOrderTraversal(root, ans);
_levelOrderTraversal(root, 0, ans);
return ans;
}
private:
queue<TreeNode*> que;
vector<int> ans;
//非递归版本
void levelOrderTraversal(TreeNode* root, vector<int>& ans) {
if(root == nullptr) return ;
int cur = 0, last, val;
TreeNode* tmp;
que.push(root);

while(cur < que.size()) {
last = que.size();
while(cur < last) {
tmp = que.front();
que.pop();
if(tmp->left) que.push(tmp->left);
if(tmp->right) que.push(tmp->right);
cur++;
}
ans.push_back(tmp->val);
cur = 0;
}
}
//递归版本
void _levelOrderTraversal(TreeNode* root, int depth, vector<int>& ans) {
if(root == nullptr) return ;
if(depth >= ans.size()) ans.push_back(root->val);
_levelOrderTraversal(root->right, depth + 1, ans);
_levelOrderTraversal(root->left, depth + 1, ans);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息