leetcode_c++:树:Binary Tree Right Side View(199)

来源:互联网 发布:python tile函数 编辑:程序博客网 时间:2024/05/16 10:05

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

假设你站在一棵树的右边,问从上到下看到的节点。

其实就是求树每一层的最右边节点。


算法

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

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

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


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