forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-zigzag-level-order-traversal(AC).cpp
More file actions
49 lines (48 loc) · 1.18 KB
/
binary-tree-zigzag-level-order-traversal(AC).cpp
File metadata and controls
49 lines (48 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <algorithm>
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: A list of lists of integer include
* the zigzag level order traversal of its nodes' values
*/
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
ans.clear();
if (root == NULL) {
return ans;
}
preorder(root, 0);
int i;
for (i = 1; i < ans.size(); i += 2) {
reverse(ans[i].begin(), ans[i].end());
}
return ans;
}
private:
vector<vector<int> > ans;
void preorder(TreeNode *root, int depth) {
if (depth + 1 > ans.size()) {
ans.push_back(vector<int>());
}
ans[depth].push_back(root->val);
if (root->left != NULL) {
preorder(root->left, depth + 1);
}
if (root->right != NULL) {
preorder(root->right, depth + 1);
}
}
};