1. 程式人生 > >LeetCode Binary Tree Right Side View : 思想上的基於佇列的廣度優先遍歷,形式上的一個簡單變種

LeetCode Binary Tree Right Side View : 思想上的基於佇列的廣度優先遍歷,形式上的一個簡單變種

題目: 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;

 }

};