首页 > 其他 > 详细

Binary Tree Right Side View--LeetCode

时间:2015-04-12 10:41:35      阅读:150      评论:0      收藏:0      [点我收藏+]

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;  

}



Binary Tree Right Side View--LeetCode

原文:http://blog.csdn.net/yusiguyuan/article/details/45007695

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!