LeetCode--Binary Tree Level Order Traversal
阿新 • • 發佈:2017-06-14
push_back 遞歸法 rsa comment hid 一行 code eve post
Binary Tree Level Order Traversal
這幾個題目相似。都是用同樣的遞歸法,時間空間復雜度都為O(n).
當然,還有叠代法,控件復雜度會降至 O(1),這個暫不討論。
Binary Tree Level Order Traversal
// 遞歸版,時間復雜度 O(n),空間復雜度 O(n) class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int >> result;
traverse(root, 1, result);
return result;
}
void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {
if (!root) return;
if (level > result.size())
result.push_back(vector<int>());
result[level-1 ].push_back(root->val);
traverse(root->left, level+1, result);
traverse(root->right, level+1, result);
} };
Binary Tree Level Order Traversal II
// 遞歸版,時間復雜度 O(n),空間復雜度 O(n)
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) { vector <vector<int>> result;
traverse(root, 1, result);
std::reverse(result.begin(), result.end()); // 比上一題多此一行 return result;
}
void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {
if (!root) return;
if (level > result.size())
result.push_back(vector<int>());
result[level-1].push_back(root->val);
traverse(root->left, level+1, result);
traverse(root->right, level+1, result);
} };
Binary Tree Zigzag Level Order Traversal
// 遞歸版,時間復雜度 O(n),空間復雜度 O(n)
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>> result;
traverse(root, 1, result, true);
return result;
}
void traverse(TreeNode *root, size_t level, vector<vector<int>> &result,
bool left_to_right) {
if (!root) return;
if (level > result.size())
result.push_back(vector<int>());
if (left_to_right)
result[level-1].push_back(root->val);
else
result[level-1].insert(result[level-1].begin(), root->val);
traverse(root->left, level+1, result, !left_to_right);
traverse(root->right, level+1, result, !left_to_right);
}
};
LeetCode--Binary Tree Level Order Traversal