1. 程式人生 > >[leetcode] 103 Binary Tree Zigzag Level Order Traversal (Medium)

[leetcode] 103 Binary Tree Zigzag Level Order Traversal (Medium)

原題連結

題目要求以“Z”字型遍歷二叉樹,並存儲在二維數組裡。 利用BFS,對每一層進行遍歷。對於每一層是從左還是從右,用一個整數型判斷當前是偶數行還是奇數行就可以了。

class Solution
{
public:
  vector<vector<int>> res;
  vector<vector<int>> zigzagLevelOrder(TreeNode *root)
  {
    if (root == NULL)
      return res;
    stack<TreeNode *> sta;
    sta.push(root);
    TravelNextLevel(sta, 1);
    return res;
  }

private:
  void TravelNextLevel(stack<TreeNode *> &sta, int level)
  {
    res.emplace_back();
    res.back().reserve(sta.size());
    stack<TreeNode *> nextSta;
    while (!sta.empty())
    {
      TreeNode *curNode = sta.top();
      sta.pop();
      res.back().push_back(curNode->val);
      if (level % 2 != 0)
      {
        if (curNode->left)
          nextSta.push(curNode->left);
        if (curNode->right)
          nextSta.push(curNode->right);
      }

      if (level % 2 == 0)
      {
        if (curNode->right)
          nextSta.push(curNode->right);
        if (curNode->left)
          nextSta.push(curNode->left);
      }
    }

    if (!nextSta.empty())
      TravelNextLevel(nextSta, level + 1);
  }
};