# [Leetcode][Python/Java]Binary Tree Level Order Traversal/二叉树层序遍历

【Leetcode题解】 同时被 2 个专栏收录
146 篇文章 0 订阅
145 篇文章 10 订阅

## 代码

### Java

import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}

ArrayList<Integer> result = new ArrayList<>();
while (!deque.isEmpty()) {
TreeNode t = deque.pop();
if (t.left != null) {
}
if (t.right != null) {
}
}
return result;
}
}


### Python

#### 迭代

class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
tree = []
if not root:
return tree
curr_level = [root]
# print(type(root), type(curr_level))  # (<class 'precompiled.treenode.TreeNode'>, <type 'list'>)
# print(curr_level)  # 作为list，却并不能遍历整个树
while curr_level:
level_list = []
next_level = []
for temp in curr_level:
level_list.append(temp.val)
if temp.left:
next_level.append(temp.left)
if temp.right:
next_level.append(temp.right)
tree.append(level_list)
curr_level = next_level
return tree


#### 递归

class Solution(object):
def preorder(self, root, level, res):
if root:
if len(res) < level+1: res.append([])
res[level].append(root.val)
self.preorder(root.left, level+1, res)
self.preorder(root.right, level+1, res)

def levelOrder(self, root):
res=[]
self.preorder(root, 0, res)
return res


## 总结

1. 正如代码注释，将root外面加括号使得其变为了list。但在下面的for循环中，依然其是作为一个树结构存储的，是否可以理解为这里的括号仅仅是将他变得可被遍历。
之后我print(temp)得到了：
<precompiled.treenode.TreeNode object at 0x7fbb9a294b50>
<precompiled.treenode.TreeNode object at 0x7fbb9a294d50>
<precompiled.treenode.TreeNode object at 0x7fbb9a294d90>
<precompiled.treenode.TreeNode object at 0x7fbb9a294dd0>
<precompiled.treenode.TreeNode object at 0x7fbb9a294e10>


• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

08-23 4141
04-09 6471
05-05 22
03-03 332
©️2021 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。