Binary Tree Right Side View
  1. 问题

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

  2. 解答
    class Solution1 {
    public:
        vector<int> rightSideView(TreeNode* root) {
            vector<int> res;
            
            while(root)
            {
                res.push_back(root->val);
                TreeNode *f1;
                
                if(root->right==NULL)
                {
                   f1=root->left;
                   if(f1==NULL) break;
                }
                else
                   f1=root->right;
                   
                root=f1;
            }
            
            return res;
        }
    };
    
    class Solution {
    public:
        vector<int> rightSideView(TreeNode *root) {
            vector<int> ans;
            if (root == nullptr) return ans;
            queue<TreeNode*> que;
            que.push(root);
            TreeNode* curr;
            while(!que.empty()) {
                int cnt = que.size();
                for (int i = 0; i < cnt; i++) {
                    curr = que.front(); que.pop();
                    if (curr->left) {
                        que.push(curr->left);
                    }
                    if (curr->right) {
                        que.push(curr->right);
                    }
                }
                ans.push_back(curr->val);
            }
            return ans;
        }
    };


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012201343/article/details/49948573
文章标签: 二叉树
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Binary Tree Right Side View

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭