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]
.
思路:相当于层次遍历,只不过需要注意的是指输出这一层的最后一个元素。
void rightSideView(BinTree *root) { vector<int> vec; deque<BinTree*> de; if(root == NULL) return ; int curnum = 1; int nexnum=0; de.push_back(root); BinTree* temp; while(!de.empty()) { while(curnum >0) { temp = de.front(); if(curnum ==1) vec.push_back(temp->value); de.pop_front(); curnum--; if(temp->left != NULL) { de.push_back(temp->left); nexnum++; } if(temp->right != NULL) { de.push_back(temp->right); nexnum++; } } curnum = nexnum; nexnum=0; } for(int i=0;i<vec.size();i++) cout<<vec[i]<<" "; cout<<endl; }
时间: 2024-10-07 14:53:40