Leetcode-199. Binary Tree Right Side View

来源:互联网 发布:软件界面的英文 编辑:程序博客网 时间:2024/06/01 22:24

题目

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].
返回二叉树每一层最右边的节点的值

思路

在 Leetcode-102. Binary Tree Level Order Traversal的基础上,最后只须将每一层的最后一个元素加入结果集即可

代码

class Solution {public:    vector<int> rightSideView(TreeNode* root) {        vector<int> res;        if(!root)            return res;        queue<TreeNode*> que[2];        int flag = 0;        que[flag].push(root);        while(!que[flag].empty()) {            vector<int> cur;            while(!que[flag].empty()) {                TreeNode* t = que[flag].front();                que[flag].pop();                cur.push_back(t->val);                if(t->left)                    que[(flag+1)%2].push(t->left);                if(t->right)                    que[(flag+1)%2].push(t->right);            }            res.push_back(cur[cur.size()-1]);            flag = (flag+1)%2;        }        return res;    }};
0 0
原创粉丝点击