[Lc]面试题32_II从上到下打印二叉树II
Contents
题目
题解
二叉树结构如下:
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
1. 队列迭代法
比上一题稍微复杂一点,不同层次要分开存,因此这里要多一个循环,先存一层的数,再一起放入res,详见102题注释
- 时间复杂度$O(n)$
- 空间复杂度$O(n)$
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> q({root});
while(!q.empty()){
vector<int> thisLevel;
int levelSize = q.size();
while(levelSize--){
auto tmp = q.front();q.pop();
thisLevel.push_back(tmp->val);
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
res.push_back(thisLevel);
}
return res;
}
};
2. 递归法
详见103题注释
- 时间复杂度$O(n)$
- 空间复杂度$O(n)$
class Solution {
vector<vector<int>> res;
public:
void dfs(TreeNode* cur, int level){
if(!cur) return;
if(level == res.size()) res.push_back({});
res[level].push_back(cur->val);
dfs(cur->left, level+1);
dfs(cur->right, level+1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
if(!root) return res;
dfs(root,0);
return res;
}
};
Author ChrisHRZ
LastMod 2020-05-18