劍指Offer Python 從上往下列印二叉樹

2021-08-22 10:04:12 字數 1392 閱讀 1016

題目:從上往下列印二叉樹

從上往下列印出二叉樹的每個節點,同層節點從左至右列印。

# -*- coding:utf-8 -*-

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class

solution:

# 返回從上到下每個節點值列表,例:[1,2,3]

defprintfromtoptobottom

(self, root):

# write code here

if root is

none:

return

pre_level = [root]

res = [root.val]

next_level =

while

true:

while pre_level:

cur_node = pre_level.pop(0)

if cur_node.left:

if cur_node.right:

if next_level == :

break

pre_level = next_level

next_level =

return res

簡介版

# -*- coding:utf-8 -*-

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class

solution:

# 返回從上到下每個節點值列表,例:[1,2,3]

defprintfromtoptobottom

(self, root):

# write code here

if root is

none:

return

res =

cur_stack = [root]

while cur_stack:

nxt_stack =

for i in cur_stack:

if i.left:

if i.right:

cur_stack = nxt_stack

return res

劍指offer(Python)替換空格

這道題要求是 將乙個字串中的空格替換成 20 有多少個空格就替換成多少個 20 例如 hello world 中間有兩個空格,則需要輸出的形式是 hello 20 20world 字串首尾的空格亦算在內。class solution def replacespace self,s return 20...

劍指offer Python 替換空格

請實現乙個函式,將乙個字串中的每個空格替換成 20 python字串,有replace方法,可以實現替換,第乙個引數是要替換的內容,第二個引數是替換的新內容 能夠快速完成,果然python作為一種高階語言,不太適合做演算法 但是 replace 相當於 insert 在替換 時,會將原字串元素的位置...

《劍指offer》python 動態規劃

動態規劃是利用空間去換取時間的演算法.主要看 1.初始條件 2.重疊子問題 3.狀態轉移方程 題目描述 乙隻青蛙一次可以跳上1級台階,也可以跳上2級。求該青蛙跳上乙個n級的台階總共有多少種跳法 先後次序不同算不同的結果 coding utf 8 class solution def jumpfloo...