Skip to content

Latest commit

 

History

History
58 lines (46 loc) · 1.08 KB

0199._Binary_Tree_Right_Side_View.md

File metadata and controls

58 lines (46 loc) · 1.08 KB

199. Binary Tree Right Side View

难度: Medium

刷题内容

原题连接

内容描述

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

示例:

输入: [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;
}