[BFS]199. Binary Tree Right Side View

题目:

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


题目分析:

1、根据题目要求,我们要站在树的“右侧”的角度去观察一棵树,并把观察到的结果通过一个vector<int>作为答案返回;实际上就是让我们找出二叉树每一行的最右侧结点的元素值。很明显,这道题应该用BFS算法。

2、BFS算法本身是可以通过队列实现的,我们需要做的就是在队列实现BFS的同时设置参数去找到每一行结束的结点。这里的想法是设置两个变量th(this)、ne(next)分别表示本层的节点数目和下一层的节点数目。对于每一层通过th次循环,按照BFS将本层的结点的子节点放入queue中,在循环结束时将最后一个元素(即本层最后一个元素)的值压入答案容器中。并在循环结束后重新初始化th和ne(将ne的值赋给th,ne清零)以进入下一次循环。


代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
#include<queue>

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        if(root == NULL)
        	return res;
        queue<TreeNode*> Q;
        Q.push(root);
		int th = 1;
        int ne = 0;
        while(!Q.empty()){
        	for(int i = 0; i < th; i++){
        		TreeNode* Node = Q.front();
        		if(Node->left != NULL){
        			Q.push(Node->left);
        			ne++;
        		}
        		if(Node->right != NULL){
        			Q.push(Node->right);
        			ne++;
        		}
        		if(i == th - 1){
        			res.push_back(Node->val);
        		}
        		Q.pop();
        	}
        	th = ne;
        	ne = 0;
        }
        return res;
	}
};
总结:
1、首先这道题的思路在之前的一道题中已经使用过,所以会相对比较熟悉。
2、有个难点就是在建立内部循环时,对于pop()、参数初始化以及压入答案值应置于循环外还是循环内需要仔细考量。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值