- leet_code:地址
- 问题描述:给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
- 测试用例:
- 输入:[1,2,3,null,5,null,4]
- 输出:[1, 3, 4]
- 解题方法:
- 二叉树层次遍历法:
- 注意点:1、注意边界条件(二叉树为空等等)2、对每一层的节点数进行统计,以计算出每层中最后一个节点(最右侧节点)
- c++代码:
- 二叉树层次遍历法:
#include<iostream>
using namespace std;
#include<queue>
class TreeNode
{
public:
int value;
TreeNode *left;
TreeNode *right;
TreeNode() {};
TreeNode(int val, TreeNode *l, TreeNode *r):value(val), left(l), right(r){}
};
class Solution
{
public:
queue<int> rightSideView(TreeNode *a)
{
queue<TreeNode> que;
queue<int> res;
if (!a)
return res;
que.push(*a);
while (!que.empty())
{
int n = que.size();
while (n--)
{
TreeNode tmp = que.front();
if (n == 0)
{
res.push(tmp.value);
cout << tmp.value << endl;
}
que.pop();
if (tmp.left != NULL)
que.push(*(tmp.left));
if (tmp.right != NULL)
que.push(*(tmp.right));
}
}
return res;
}
};
- 二叉树深度优先遍历方法(并且使用递归实现)
- 注意点:1、利用二叉树先根序遍历,并且先遍历右子树再遍历左子树
- c++代码:
void DFS_rightSideView(TreeNode *a, queue<int> &res, int level)
{
if (!a)
return;
if (res.size() < level + 1)
{
res.push(a->value);
cout << a->value << endl;
}
DFS_rightSideView(a->right, res, level + 1);
DFS_rightSideView(a->left, res, level + 1);
}
主函数调用部分:
int main(int argc, char *argv[])
{
TreeNode a(1, NULL, NULL), b(2, NULL, NULL), c(3, NULL, NULL), d(5, NULL, NULL), e(4, NULL, NULL);
a.left = &b;
a.right = &c;
b.right = &d;
c.right = &e;
Solution solution;
TreeNode *ptr = &a;
solution.rightSideView(ptr);
system("pause");
}