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

    好久不写了,最近忙毕业论文呢。

    这个题,就是说一个二叉树,你从右边看,你能看到的数有哪些(会被遮挡)

    其实抽象出来就是说。。。二叉树每层最右边的数有哪些。。

    那我们按层遍历一次就好了。

    /**
     * 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) {
            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;
        }
    };
    

      

  • 相关阅读:
    Redis安装配置
    Git本地服务器搭建
    JDK安装配置
    ssh免密登录
    设计模式
    IDEA 快捷键
    LeetCode Sliding Window Maximum
    ElasticSearch 使用小结
    LeetCode Product of Array Except Self
    LeetCode Delete Node in a Linked List
  • 原文地址:https://www.cnblogs.com/x1957/p/4420101.html
Copyright © 2011-2022 走看看