Skip to content

199. Binary Tree Right Side View

难度: Medium

刷题内容

原题连接

  • https://leetcode-cn.com/problems/binary-tree-right-side-view/

内容描述

``` 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4] 输出: [1, 3, 4] 解释:

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

解题方案

思路 1

二叉树层次遍历
vector<int> rightSideView(TreeNode* root) {
    vector<int> ans;
    if(root==NULL)
        return ans;
    vector<TreeNode*> stack;
    stack.push_back(root);

    while(!stack.empty()){
        vector<TreeNode*> tmp;
        TreeNode* node;
        for(int i=0;i<stack.size();i++){
            node = stack[i];
            if(node->left)
                tmp.push_back(node->left);
            if(node->right)
                tmp.push_back(node->right);
        }
        ans.push_back(node->val);
        stack = tmp;
    }
    return ans;
}

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组