Question
从上往下打印二叉树
关键词:二叉树 BFS 队列结构
Solution
BFS
开辟新数组,储存当前层的结点。
时间复杂度:O(N)
空间复杂度:O(log(N))
- Python
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
if not root:
return []
ans = []
nodes = [root]
while nodes:
cur = nodes.pop(0)
ans.append(cur.val)
if cur.left:
nodes.append(cur.left)
if cur.right:
nodes.append(cur.right)
return ans
- C++
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> ans;
if(!root)
return ans;
vector<TreeNode*> nodes;
nodes.push_back(root);
int j = 0;
while(j<nodes.size()){
TreeNode* cur = nodes[j];
j++;
ans.push_back(cur->val);
if(cur->left)
nodes.push_back(cur->left);
if(cur->right)
nodes.push_back(cur->right);
}
return ans;
}
};