LeetCode 199 - 二叉树的右视图

题目描述

199. 二叉树的右视图

解法:层遍历(C++)

思路很简单,就是层遍历到该层最右的节点,就将这个节点的值放入结果数组中

/**
 * 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==nullptr) return res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            int n = q.size();
            for(int i=0;i<n;i++)
            {
                TreeNode* tmp = q.front();
                q.pop();
                if(tmp->left!=nullptr) q.push(tmp->left);
                if(tmp->right!=nullptr) q.push(tmp->right);
                if(i==n-1) res.push_back(tmp->val);
            }
        }
        return res;
    }
};
发布了189 篇原创文章 · 获赞 36 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_38204302/article/details/105689942