1. 程式人生 > >[劍指offer] 59. 按之字形順序列印二叉樹

[劍指offer] 59. 按之字形順序列印二叉樹

題目描述

請實現一個函式按照之字形列印二叉樹,即第一行按照從左到右的順序列印,第二層按照從右至左的順序列印,第三行按照從左到右的順序列印,其他行以此類推
思路: 用兩個棧或佇列去儲存,用一個變量表示方向,根據不同方向存取順序不同。
class Solution
{
  public:
    vector<vector<int>> Print(TreeNode *pRoot)
    {
        vector<vector<int>> res;
        if (pRoot == NULL)
            
return res; int direct = 1; stack<TreeNode *> staO; stack<TreeNode *> staE; TreeNode *cur; staO.push(pRoot); while (!staO.empty() || !staE.empty()) { vector<int> temp; if (direct % 2 != 0) {
while (!staO.empty()) { cur = staO.top(); staO.pop(); temp.push_back(cur->val); if (cur->left != NULL) staE.push(cur->left); if (cur->right != NULL) staE.push(cur
->right); } res.push_back(temp); direct = 2; } else { while (!staE.empty()) { cur = staE.top(); staE.pop(); temp.push_back(cur->val); if (cur->right != NULL) staO.push(cur->right); if (cur->left != NULL) staO.push(cur->left); } res.push_back(temp); direct = 1; } } return res; } };