Sword refers to offer (C++)-JZ77: print binary tree in zigzag order (data structure - tree)

Author: Steven Zhai
Copyright Notice: The copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source

Topic description:

Given a binary tree, return the zigzag traversal of the binary tree, (the first layer is from left to right, the next layer is from right to left, and so on)

Data range: 0≤n≤1500, the val of each node on the tree satisfies the requirement of ∣val∣<=100
: space complexity: O(n), time complexity: O(n)

For example:
the given binary tree is {1,2,3,#,#,4,5}

The result of the zigzag traversal of the binary tree is

[

[1],

[3,2],

[4,5]

]

 

Example:

enter:

{1,2,3,#,#,4,5}

return value:

[[1],[3,2],[4,5]]

illustrate:

As explained in the title, the first layer is the root node, the results are printed from left to right, the second layer is from right to left, and the third layer is from left to right.

Problem solving ideas:

This question examines the use of data structure trees. The problem is solved by using the first-in-first-out feature of the queue. When a certain layer is executed, the value of the current layer is put into the vector for retention, and then the node pointer is popped out of the queue and stored in the next layer of the node pointer to the queue; each The layer performs parity judgment, the even-numbered layer reverses the vector, and puts the vector of this layer into the vector<vector<int>>; finally, the sequential printing of the zigzag is realized.

Test code:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> v;
        if(!pRoot)
            return v;
        queue<TreeNode*> q;
        q.push(pRoot);
        int l=0;
        // 遍历所有结点
        while(!q.empty())
        {
            int size=q.size();
            vector<int> a;
            // 遍历存放左右子树结点
            while(size--)
            {
                TreeNode* n=q.front();
                q.pop();
                a.push_back(n->val);
                if(n->left)
                    q.push(n->left);
                if(n->right)
                    q.push(n->right);
            }
            l++;
            // 如果l是偶数层,则将vector反转
            if(l%2==0)
                reverse(a.begin(), a.end());
            v.push_back(a);
        }
        return v;
    }
    
};

Guess you like

Origin blog.csdn.net/zhaitianbao/article/details/122255122