Binary Tree Right Side View

来源:互联网 发布:淘宝禁止出售保护动物 编辑:程序博客网 时间:2024/04/29 01:43

题目:

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


思想:

从右面看二叉树,我们所能看到的是每一层的最右的一个数,为此本题可以采用层次遍历的方式,每次只记录每一层的最后一个数字即可。


代码:

/*** Definition for a binary tree node.* */typedef struct TreeNode {     int val;     TreeNode *left;     TreeNode *right;     TreeNode(int x) : val(x), left(NULL), right(NULL) {} }*BinaryTree;class Solution {public:void CreateTree(BinaryTree &T){char data;cin >> data;if (data == '#')T = NULL;else{T = new TreeNode(data - '0');CreateTree(T->left);CreateTree(T->right);}}vector<int> rightSideView(TreeNode* root) {queue<TreeNode*> q;TreeNode* temp = new TreeNode(NULL);TreeNode* p = NULL;vector<int> ret;if (root==NULL){return ret;}q.push(root);q.push(NULL);int pre;//用于保存每一层的最后一个数字while (!q.empty()){ p = q.front(); while (p!=NULL) { if (p->left!=NULL) { q.push(p->left); } if (p->right!=NULL) { q.push(p->right); } pre = p->val; q.pop(); p = q.front(); } ret.push_back(pre); q.pop(); if (!q.empty()) {  q.push(NULL); }}return ret;}};


0 0