您的位置:首页 > 其它

LeetCode Binary Tree Right Side View : 思想上的基于队列的广度优先遍历,形式上的一个简单变种

2015-04-07 10:30 555 查看
题目: 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

 

思路 : 分别用二个队列存储上一层元素,以及基于上一层元素获得的下一层元素,并取出其最后一个元素,以此类推

 

代码:

 

class Solution

{

public:

 vector<int> rightSideView(TreeNode *root)

 {

        vector<int> result;

  if(root == NULL)

  {

      return result;

  }

  //用二个vector交替存储上一行和下一行元素

  queue<TreeNode*> top;

  queue<TreeNode*> down;

  top.push(root);

  result.push_back(root->val);

        while(!top.empty())

        {

            while(!top.empty())

            {

                TreeNode* node = top.front();

             top.pop();

           

             if(node->left)

             {

                    down.push(node->left);

             }

             if(node->right)

             {

                    down.push(node->right);

             }

            }

   if(!down.empty())

   {

                TreeNode* rightMost = down.back();

                result.push_back(rightMost->val);

   }

   while(!down.empty())

   {

                TreeNode* downNode = down.front();

                top.push(downNode);

                down.pop();

   }

  }

  

  return result;

 }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: