JZ046:二叉树的右侧视图



title: 二叉树的右侧视图


?? 题目描述

题目链接:二叉树的右侧视图、相同题目

image-20220511225725833

?? 解题思路

方法一:队列层次遍历(bfs)

class Solution {
public:
    vector rightSideView(TreeNode* root) {
        vector res;
        queue que;
        if (root == nullptr) return res;
        que.push(root);
        while (!que.empty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                TreeNode *node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
                if (i == size - 1) res.push_back(node->val);
            }
        }
        return res;
    }
};

方法二:dfs

关键点:用一个depth记录一层的视点 节点是否找到

class Solution {
public:
    vector res;
    vector rightSideView(TreeNode* root) {
        if (root == nullptr) return res;
        dfs(root, 0);
        return res;
    }
    void dfs(TreeNode *root, int depth) {
        if (depth == res.size()) res.emplace_back(root->val);
        
        if (root->right) dfs(root->right, depth + 1);
        if (root->left) dfs(root->left, depth + 1);
    }
};

?? 复杂度分析

  • 时间复杂度:o(n)
  • 空间复杂度:O(n),考虑最坏情况树变成链表;