199.二叉树的右视图

199.二叉树的右视图_第1张图片
参考评论区的代码:
层次遍历:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if(!root) return {};
        vector<int> res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int size=q.size();留最右边的
            res.push_back(q.front()->val);
            while(size){
                TreeNode *temp=q.front();
                q.pop();
                if(temp->right) q.push(temp->right);//右先入队
                if(temp->left) q.push(temp->left);
                size--;
            }
        }
        return res;
    }

};

在这里插入图片描述

深度优先遍历:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        right(root,res,0);
        return res;
    }

    void right(TreeNode *root,vector<int> &res,int h){
        if(root){
            if(res.size()==h) res.push_back(root->val);
            right(root->right,res,h+1);
            right(root->left,res,h+1);
        }
    }
};

在这里插入图片描述

你可能感兴趣的:(力扣,深度优先,算法)