Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (i.e.from left to right, then right to left for the next level andalternate 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] ]
Personally I think,
time complexity = O(n * height), n is the number of nodes, height is the height of the given binary tree.getHeight() => O(n) traverseSpecificLevel() => O(n) reverseVector() => O(n) swap() => O(1)
C++
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>> list;
// Input validation.
if (root == NULL) return list;
// Get the height of the binary tree.
int height = getHeight(root);
bool left_to_right = true;
for (int level = 0; level <= height; level ++) {
vector<int> subList;
traverseSpecificLevel(root, level, subList);
if (left_to_right == true) {
// Add subList into list.
list.push_back(subList);
// Update left_to_right flag.
left_to_right = false;
} else {
// Reverse subList.
reverseVector(subList);
// Add reversed subList into list.
list.push_back(subList);
// Update left_to_right flag.
left_to_right = true;
}
}
return list;
}
int getHeight(TreeNode *root) {
// Base case.
if (root == NULL || (root->left == NULL && root->right == NULL)) return 0;
else return 1 + max(getHeight(root->left), getHeight(root->right));
}
void traverseSpecificLevel(TreeNode *root, int level, vector<int> &subList) {
// Base case.
if (root == NULL) return;
if (level == 0) {
subList.push_back(root->val);
return;
}
// Do recursion.
traverseSpecificLevel(root->left, level - 1, subList);
traverseSpecificLevel(root->right, level - 1, subList);
}
void reverseVector(vector<int> &list) {
// Input validation.
if (list.size() <= 1) return;
int start = 0;
int end = list.size() - 1;
while (start < end) {
swap(list, start, end);
start ++;
end --;
}
}
void swap(vector<int> &list, int first, int second) {
int tmp = list[first];
list[first] = list[second];
list[second] = tmp;
}
};
You can do it in linear time. Create a vector > result with size max_height. Traverse a tree recursively maintaining a level of a node. For every node push back its value to a result[level]. Than just reverse result[1], result[3], ... .
By the way, there is a swap(x,y)
function and reverse(a.begin(), a.end())
function (where a
is a vector), you may use them instead of implementing them by yourself. Include algorithm
for it.