[LeetCode]199. Binary Tree Right Side View

二叉树的层次遍历,从右往左看

Posted by JinFei on March 4, 2020

题目描述

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.

Example1:

Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation:

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

解题思路

  • 层次遍历,如果此时的i == size - 1,表明是该层的最后一个节点 (从右往左看)
  • 如果此时的i == 0,表示是第一个节点(可以从左往右看)
/**
 * 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) {
        vector<int> res;
        if(root == NULL){
            return res;
        }
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int size = q.size();
            for(int i = 0; i < size; i++){
                TreeNode* t = q.front();
                q.pop();
                if(i == size - 1){
                    res.push_back(t -> val);
                }
                if(t -> left){
                    q.push(t -> left);
                }
                if(t -> right){
                    q.push(t -> right);
                }
            }
        }
        return res;
    }
};