从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路一: 不用队列,👍
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
if not root:
return []
currentStack = [root]
res = []
while currentStack:
nextSatck = []
for i in currentStack:
if i.left:nextSatck.append(i.left)
if i.right:nextSatck.append(i.right)
res.append(i.val)
currentStack = nextSatck
return res
思路二: 广度优先搜索BFS,借助队列
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
if not root:
return []
queue = [root]
result = []
#queue.append(root)
while len(queue)>0:
node = queue.pop(0)
result.append(node.val)
if node.left: queue.append(node.left)
if node.right:queue.append(node.right)
return result