zoukankan      html  css  js  c++  java
  • Binary Tree Right Side View

    好久没有刷leetcode了,要继续了。。

    今天第一题。

    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].

    一看到就觉得是层次遍历,而且每层的最后一个结点会保存下来。

    C++实现代码:

    #include<iostream>
    #include<new>
    #include<vector>
    #include<queue>
    using namespace std;
    
    //Definition for binary tree
    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) {
            if(root==NULL)
                return vector<int>();
            vector<int> res;
            queue<TreeNode*> q;
            q.push(root);
            int cur=1;
            while(!q.empty())
            {
                int rcur=0;
                while(cur)
                {
                    TreeNode *tmp=q.front();
                    q.pop();
                    cur--;
                    if(cur==0)
                        res.push_back(tmp->val);
                    if(tmp->left)
                    {
                        q.push(tmp->left);
                        rcur++;
                    }
                    if(tmp->right)
                    {
                        q.push(tmp->right);
                        rcur++;
                    }
                }
                cur=rcur;
            }
            return res;
        }
        void createTree(TreeNode *&root)
        {
            int i;
            cin>>i;
            if(i!=0)
            {
                root=new TreeNode(i);
                if(root==NULL)
                    return;
                createTree(root->left);
                createTree(root->right);
            }
        }
    };
    
    int main()
    {
        Solution s;
        TreeNode *root;
        s.createTree(root);
        vector<int> vec;
        vec=s.rightSideView(root);
        for(auto a:vec)
            cout<<a<<" ";
        cout<<endl;
    }
  • 相关阅读:
    CSUFT 1002 Robot Navigation
    CSUFT 1003 All Your Base
    Uva 1599 最佳路径
    Uva 10129 单词
    欧拉回路
    Uva 10305 给任务排序
    uva 816 Abbott的复仇
    Uva 1103 古代象形文字
    Uva 10118 免费糖果
    Uva 725 除法
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4393040.html
Copyright © 2011-2022 走看看