Binary Tree Zigzag Level Order Traversal(C++二叉树的锯齿形层次遍历)

/**
 * 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>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> output;
            deque <TreeNode*> c;  //定义一个空的队列
            deque <int> layers;  //定义一个空的层次队列
            c.push_back(root);
            layers.push_back(0);
            while (!c.empty()) {  //如果队列不为空
                TreeNode* temp = c.front();  //返回队列的第一个元素
                int layer = layers.front();
                if (temp) {  //如果是非空结点
                    if (layer%2==0) { //之行结构 
                        if (layer == output.size()) {
                            vector<int> ou = {temp->val};
                            output.push_back(ou);
                        } else {
                            output[layer].push_back(temp->val);
                        }
                    } else {
                        if (layer == output.size()) {
                            vector<int> ou = {temp->val};
                            output.push_back(ou);
                        } else {
                            output[layer].insert(output[layer].begin(), temp->val);
                        }
                    }
                    c.pop_front();  //出队列
                    layers.pop_front();

                    c.push_back(temp->left);  //左孩子
                    c.push_back(temp->right); //右孩子

                    layers.push_back(layer+1);
                    layers.push_back(layer+1);
                }
                else {
                    c.pop_front();  //出队列
                    layers.pop_front();
                }
            }
            return output; 
        }
};
发布了264 篇原创文章 · 获赞 272 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105356854