[Leetcode] 199. Binary Tree Right Side View 解题报告

本文介绍了二叉树右视图问题的两种解决方案:深度优先搜索(DFS)与广度优先搜索(BFS)。通过具体示例展示了如何从二叉树的顶部到底部返回可以看到的节点值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

For example:
Given the following binary tree,

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

You should return [1, 3, 4].

思路

这道题目的本质是一个树的遍历问题,只是我们在遍历过程中需要记录每层最右边的结点值。树的遍历有DFS和BFS两种策略,这两种策略都可以用来求解本题目。

1、DFS:我们采用先序遍历,以保证越靠近根节点的结果越处于结果前列。特殊之处在于遍历完根节点之后,先遍历右子树,再遍历左子树(这样可以保证每个层次中第一个被遍历到的结点一定是该层的最右边结点),并且维护一个还没有被遍历到的层的索引,如果当前结点的层数大于未遍历到的层数,说明我们进入了一个新层,所以将当前节点的值加入结果集中。

2、BFS:BFS求解本题目实际上更直观。我们按照层次遍历,每次遍历到一个层次的末尾时,就将该层的最右边结点的值加入结果集中。下面的代码片段采用队列这种数据结构实现了层次遍历,并采用添加NULL值这种技巧区分层。

代码

1、DFS:

/**
 * 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> ret;
        int depth = 0;
        DFS(root, 1, ret, depth);
        return ret;
    }
private:
    void DFS(TreeNode* root, int current_depth, vector<int> &ret, int &depth) {
        if (!root) {
            return;
        }
        if (depth < current_depth) {    // came to a new depth
            ++depth;ret.push_back(root->val);
        }
        DFS(root->right, current_depth + 1, ret, depth);
        DFS(root->left, current_depth + 1, ret, depth);
    }
};

2、BFS:

/**
 * 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> ret;
        if (!root) {
            return ret;
        }
        queue<TreeNode*> q;
        q.push(root), q.push(NULL);
        int value;
        while (!q.empty()) {
            TreeNode *node = q.front();
            q.pop();
            if (node == NULL) {         // come to the end of a layer
                ret.push_back(value);
                if (!q.empty()) {
                    q.push(NULL);
                }
            }
            else {
                value = node->val;
                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值