二叉树之
字形级别顺序遍历给定一棵二叉树,返回其节点值的之字形级别顺序遍历。(即从左到右,然后从右到左为下一级和交替)。例如:给定二叉树 {3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
将其之字形水平顺序遍历返回为:
[ [3], [20,9], [15,7] ]
个人认为,
时间复杂度= O(n * height),n是节点数,height是给定二叉树的高度。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;
}
};