leetcode:Binary Tree Zigzag Level Order Traversal

来源:互联网 发布:小米3微信无法连接网络 编辑:程序博客网 时间:2024/06/06 05:35

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.


/** * 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) {                vector<vector<int> > retVtr;        stack<TreeNode*> parentStack;                if (!root)            return retVtr;                    parentStack.push(root);        bool toggle = false;        while (!parentStack.empty())        {            vector<int> curVtr;            stack<TreeNode*> curStack;            while (parentStack.size() > 0)            {                TreeNode *pCurNode = parentStack.top();                curVtr.push_back(pCurNode->val);                            if (!toggle)                {                    if (pCurNode->left)                        curStack.push(pCurNode->left);                                    if (pCurNode->right)                        curStack.push(pCurNode->right);                }                else                {                    if (pCurNode->right)                        curStack.push(pCurNode->right);                                            if (pCurNode->left)                        curStack.push(pCurNode->left);                }                parentStack.pop();            }            toggle = !toggle;            retVtr.push_back(curVtr);            parentStack = curStack;        }            return retVtr;    }};


0 0
原创粉丝点击