[LeetCode] Binary Tree Zigzag level order traversal

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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


ALternative stacks


/**
 * Definition for binary tree
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<vector<int>> result;
        if(root==NULL)
            return result;
        
        stack<TreeNode*> stack1;
        stack<TreeNode*> stack2;
        stack1.push(root);
        
        while(!stack1.empty() || !stack2.empty())
        {
            vector<int> newlevel1;
            while(!stack1.empty())
            {
                TreeNode* node=stack1.top();
                newlevel1.push_back(node->val);
                stack1.pop();
                
                if(node->left!=NULL) stack2.push(node->left);
                if(node->right!=NULL) stack2.push(node->right);
            }
            if(newlevel1.size()!=0)
                result.push_back(newlevel1);
                
            vector<int> newlevel2;
            while(!stack2.empty())
            {
                TreeNode* node=stack2.top();
                newlevel2.push_back(node->val);
                stack2.pop();
                
                if(node->right!=NULL) stack1.push(node->right);
                if(node->left!=NULL) stack1.push(node->left);
            }
            if(newlevel2.size()!=0)
                result.push_back(newlevel2);
        }
        
        return result;
    }
};


你可能感兴趣的:([LeetCode] Binary Tree Zigzag level order traversal)