【Leetcode】103. Binary Tree Zigzag Level Order Traversal(Z型按层遍历二叉树)

版权声明:本文为博主原创文章,未经博主许可允许转载。 https://blog.csdn.net/qq_29600137/article/details/89331630

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

题目大意:

对给出的二叉树进行Z型输出。

解题思路:

102题的基础上对每一层的插入,输出进行调整。

/**
 * 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> > ans;
        
        if(root==NULL){
            return ans;
        }
        bool state = true;
        deque<TreeNode*> c;
        
        c.push_front(root);
        
        while(c.size()){
            ans.resize(ans.size() + 1);
            if(state){
                for(int i = 0, og_size = c.size();i != og_size; i++){
                    auto tmp = c.front();
                    c.pop_front();
                    ans.back().push_back(tmp->val);
                    if(tmp->left) c.push_back(tmp->left);
                    if(tmp->right) c.push_back(tmp->right);
                }
                state = false;
            }else{
                for(int i = 0, og_size = c.size();i != og_size; i++){
                    auto tmp = c.back();
                    c.pop_back();
                    ans.back().push_back(tmp->val);
                    if(tmp->right) c.push_front(tmp->right);
                    if(tmp->left) c.push_front(tmp->left);
                }
                state = true;
            }
            
        }
        
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_29600137/article/details/89331630