关闭

Binary Tree Right Side View

标签: 二叉树
137人阅读 评论(0) 收藏 举报
分类:
  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;
        }
    };


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9862次
    • 积分:515
    • 等级:
    • 排名:千里之外
    • 原创:42篇
    • 转载:7篇
    • 译文:0篇
    • 评论:0条