leetcode199. Binary Tree Right Side View

题目描述

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.

Example:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

代码

深度优先搜索

如果按正确的顺序访问每个节点,就可以有效地获得二叉树的右视图。

上面提到的顺序之一可以由深度优先搜索定义。在深度优先搜索中,我们总是先访问右子树。这样就保证了当我们访问树的某个特定深度时,我们正在访问的节点总是该深度的最右侧节点。于是,可以存储在每个深度访问的第一个结点,一旦我们知道了树的层数,就可以得到最终的结果数组。

#include <iostream>
#include <vector>

using namespace std;


/// DFS
/// Time Complexity: O(n)
/// Space Complexity: O(h)

/// 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 {

private:
    vector<int> res;

public:
    vector<int> rightSideView(TreeNode* root) {

        if(!root) return res;

        dfs(root, 0);
        return res;
    }

private:
    void dfs(TreeNode* node, int d){

        if(res.size() <= d) res.push_back(0);
        res[d] = node->val;

        if(node->left) dfs(node->left, d + 1);
        if(node->right) dfs(node->right, d + 1);
    }
};


int main() {

    return 0;
}

思路二

广度优先搜索

就像深度优先搜索可以保证我们最先访问某个深度的最右结点那样,广度优先搜索可以保证我们 最后 访问它。

通过执行将左结点排在右结点之前的广度优先搜索,我们对每一层都从左到右访问。因此,通过只保留每个深度最后访问的结点,我们就可以在遍历完整棵树后得到每个深度最右的结点

#include <iostream>
#include <vector>

using namespace std;


/// BFS
/// Time Complexity: O(n)
/// Space Complexity: O(n)

/// 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) return res;

        vector<TreeNode*> cur = {root};
        while(cur.size()){
            res.push_back(cur.back()->val);

            vector<TreeNode*> next;
            for(TreeNode* node: cur){
                if(node->left) next.push_back(node->left);
                if(node->right) next.push_back(node->right);
            }
            cur = next;
        }
        return res;
    }
};


int main() {

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值