Created
December 29, 2012 14:06
-
-
Save pdu/4407122 to your computer and use it in GitHub Desktop.
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).
http://www.leetcode.com/onlinejudge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <algorithm> | |
| using namespace std; | |
| /** | |
| * Definition for binary tree | |
| * struct TreeNode { | |
| * int val; | |
| * TreeNode *left; | |
| * TreeNode *right; | |
| * TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
| * }; | |
| */ | |
| class Solution { | |
| public: | |
| void dfs(vector< vector<int> >& ret, int& maxDepth, int curDepth, TreeNode* root) { | |
| if (root == NULL) { | |
| return; | |
| } | |
| if (curDepth > maxDepth) { | |
| maxDepth = curDepth; | |
| ret.resize(curDepth + 1); | |
| } | |
| ret[curDepth].push_back(root->val); | |
| dfs(ret, maxDepth, curDepth + 1, root->left); | |
| dfs(ret, maxDepth, curDepth + 1, root->right); | |
| } | |
| vector<vector<int> > zigzagLevelOrder(TreeNode *root) { | |
| vector< vector<int> > ret; | |
| int maxDepth = -1; | |
| dfs(ret, maxDepth, 0, root); | |
| for (int i = 1; i <= maxDepth; i += 2) { | |
| reverse(ret[i].begin(), ret[i].end()); | |
| } | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment