Binary Tree Right Side View

来源:互联网 发布:淘宝优惠券推广渠道 编辑:程序博客网 时间:2024/06/05 10:45

原题:
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].

解题:
其实考察的是树的层序遍历,每遍历一层就存储这一层左右边的元素(从右向左看),递归实现即可,比较简单。可以AC的C++代码如下:

vector<int> rightSideView(TreeNode* root) {        queue<TreeNode* > q;        vector<int> ret;        if(!root)           return ret;        TreeNode *pCur;        q.push(root);        queue<TreeNode* > layer, temp;        while(!q.empty()){            while(!q.empty()){                pCur = q.front();                q.pop();                if(q.size() == 0)                     ret.push_back(pCur->val);                if(pCur->left){                    layer.push(pCur->left);                }                if(pCur->right){                    layer.push(pCur->right);                }            }            temp = q;            q = layer;            layer = temp;        }        return ret;    }
0 0
原创粉丝点击