- LintCode 71. Binary Tree Zigzag
- leetcode--binary-tree-zigzag-lev
- [leetcode] 103. Binary Tree Zigz
- Leetcode 103. Binary Tree Zigzag
- 103. Binary Tree Zigzag Level Or
- 103. Binary Tree Zigzag Level Or
- 103 Binary Tree Zigzag Level Ord
- 103. Binary Tree Zigzag Level Or
- 103 Binary Tree Zigzag Level Ord
- Binary Tree Zigzag Level Order T
原题
LintCode 71. Binary Tree Zigzag Level Order Traversal
Description
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).
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]
]
代码
class Solution {
public:
/*
* @param root: A Tree
* @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
*/
vector<vector<int>> zigzagLevelOrder(TreeNode * root) {
// write your code here
helper(root, 0);
return ans;
}
private:
vector<vector<int>> ans;
void helper(TreeNode * root, int depth) {
if (root == NULL) return;
if (ans.size() < depth + 1) {
ans.push_back(vector<int>());
}
if (depth % 2) {
ans[depth].insert(ans[depth].begin(), root->val);
} else {
ans[depth].push_back(root->val);
}
helper(root->left, depth + 1);
helper(root->right, depth + 1);
}
};
网友评论