码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Right Side View--LeetCode

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

标签:c++   算法   leetcode   

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

标签:c++   算法   leetcode   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!