LeetCode 199. 二叉树的右视图(Binary Tree Right Side View)

题目描述

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

   1            <---
 /   
2     3         <---
      
  5     4       <---

解题思路

本题可转化为将二叉树每一层最右节点从上到下输出,所以利用层序遍历的思想,维护一个队列,并且记录当前层剩余节点数和下一层节点总数。首先将根节点加入到队列中,每次从队列中取出一个节点,将其不为空的左右孩子放入队列中,并增加下一层节点数,减少本层节点数。当本层节点数为0时,说明遍历到了本层最右节点,所以将本节点值加入到结果集中,并将本层节点数置为下一层节点数,置下一层节点数为0.

代码

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> rightSideView(TreeNode* root) {
13         vector<int> res;
14         queue<TreeNode*> q;
15         if(root == NULL) return res;
16         q.push(root);
17         int curLevel = 1, nextLevel = 0;
18         while(q.size()){
19             TreeNode* node = q.front();
20             q.pop();
21             curLevel--;
22             if(node->left){
23                 q.push(node->left);
24                 nextLevel++;
25             }
26             if(node->right){
27                 q.push(node->right);
28                 nextLevel++;
29             }
30             if(curLevel == 0){
31                 res.push_back(node->val);
32                 curLevel = nextLevel;
33                 nextLevel = 0;
34             }
35         }
36         return res;
37     }
38 };
原文地址:https://www.cnblogs.com/wmx24/p/9518719.html