1. 程式人生 > >劍指offer 33. 之字形列印二叉樹

劍指offer 33. 之字形列印二叉樹

請實現一個函式按照之字形順序從上向下列印二叉樹。

即第一行按照從左到右的順序列印,第二層按照從右到左的順序列印,第三行再按照從左到右的順序列印,其他行以此類推。

樣例

輸入如下圖所示二叉樹[8, 12, 2, null, null, 6, 4, null, null, null, null]
    8
   / \
  12  2
     / \
    6   4
輸出:[[8], [2, 12], [6, 4]]

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution { public: vector<int> get_val(vector<TreeNode*> level) { vector<int> res; for (auto &u : level) res.push_back(u->val); return res; } vector<vector<int>> printFromTopToBottom(TreeNode* root) { vector<
vector<int>>res; if (!root) return res; vector<TreeNode*>level; level.push_back(root); res.push_back(get_val(level)); bool zigzag = true; while (true) { vector<TreeNode*> newLevel; for (auto &u :
level) { if (u->left) newLevel.push_back(u->left); if (u->right) newLevel.push_back(u->right); } if (newLevel.size()) { vector<int>temp = get_val(newLevel); if (zigzag) reverse(temp.begin(), temp.end()); res.push_back(temp); level = newLevel; } else break; zigzag = !zigzag; } return res; } };