剑指 Offer 32 - III. 从上到下打印二叉树 III

/**
 * 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<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int> > res;
        if(!root) return res;
        deque<TreeNode*> Q;
        Q.push_back(root);
        bool flag = true;
        while(!Q.empty()) {
            int n = Q.size();
            vector<int> layer;
            TreeNode* t;
            while(n) {
                if(flag) {
                    t = Q.back();
                    Q.pop_back();
                    if(t->left) Q.push_front(t->left);
                    if(t->right) Q.push_front(t->right);
                }
                else {
                    t = Q.front();
                    Q.pop_front();
                    if(t->right) Q.push_back(t->right);
                    if(t->left) Q.push_back(t->left);
                }
                layer.push_back(t->val);
                n--;
            }
            flag = !flag;
            res.push_back(layer);
        }
        return res;
    }
};

利用双端队列实现偶数层的逆序。

上一篇:javascript – 在tinyMCE富文本编辑器中的光标位置插入文本


下一篇:LeetCode:123. Best Time to Buy and Sell Stock III买卖股票的最佳时机 III(C语言)