Skip to content

Latest commit

 

History

History
34 lines (32 loc) · 1.29 KB

103. Binary Tree Zigzag Level Order Traversal.md

File metadata and controls

34 lines (32 loc) · 1.29 KB

思路

这题是102层序遍历的推广,我们只需要在合适的层翻转原始访问顺序就可以了, 普通的层序遍历可参考102题解,这里不再赘述。

C++

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>>res;
        if(root == NULL) return res;
        queue<TreeNode *>q;
        TreeNode *p;
        
        bool left_to_right = true;
        q.push(root);
        while(!q.empty()){
            vector<int>level;
            for(int i = q.size(); i > 0; i--){
                p = q.front();
                q.pop();
                level.push_back(p -> val);
                if(p -> left) q.push(p -> left);
                if(p -> right) q.push(p -> right);
            }
            if(!left_to_right) reverse(level.begin(), level.end()); // 翻转原始访问顺序
            left_to_right = !left_to_right;               
            res.push_back(level);
        }
        return res;
    }
};