您的位置:首页 > 其它

Leetcode 199 Binary Tree Right Side View

2015-04-04 15:15 567 查看

1.题目要求

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]
.

意思就是从右往左看,看到每一层最右边的那个数据。

2.分析

每一层最右边的那个数据,因此只需要按照层次遍历一遍这个二叉树,获取每一层的最右边的数据即可。
二叉树层次遍历需要的数据结构是queue,现在是怎样判断每一层遍历结束,为了解决这个问题,可以再queue中插入一个标记NULL,读取到NULL,那说明NULL之前的那个数据就是该层最右边的数据。代码如下:

class Solution {
public:
vector<int> rightSideView(TreeNode *root) {
queue<TreeNode *> myQue;
vector<int> res;
res.clear();

if (NULL == root)
{
return res;
}

myQue.push(root);
myQue.push(NULL);
TreeNode *temp1,*temp2;

while (true)
{
temp1 = myQue.front();
myQue.pop();
temp2 = myQue.front();
//myQue.pop();
if(NULL == temp1 && NULL == temp2)
break;
if(NULL == temp1)
{
myQue.push(NULL);//为下一层添加标记
continue;

}
if (NULL == temp2)//提取下一个指针,判断是否是标记NULL
{
res.push_back(temp1->val);//保存最右边的值
}

if(NULL != temp1->left)
myQue.push(temp1->left);
if (NULL != temp1->right)
{
myQue.push(temp1->right);
}
}
return res;
}
};

提交Accepted,呵呵,第一次一次性通过啊。

 

3.题目扩展,如果题目改成从左往右看呢?

思路也是一样的,也是按照层次遍历,只不过每次是从右往左遍历。只需要将上面代码36-41行做一下调换即可,也就是先保存右子节点,再保存左子节点。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: