日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Python剑指offer:分行从上到下打印二叉树

發(fā)布時(shí)間:2025/4/16 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python剑指offer:分行从上到下打印二叉树 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

從上到下按層打印二叉樹(shù),同一層的節(jié)點(diǎn)按照從左到右
的順序打印,每一層打印到第一行,例如本題中上一個(gè)問(wèn)題的二叉樹(shù)
輸出形式會(huì)是:
8
6 10
5 7 9 11

這道題和前面一道題十分類(lèi)似,也可以用一個(gè)隊(duì)列來(lái)保存要打印的節(jié)點(diǎn)。
為了把二叉樹(shù)的每一行單獨(dú)打印到一行里,我們需要兩個(gè)變量:
一個(gè)變量表示當(dāng)前層中還沒(méi)有打印的節(jié)點(diǎn)數(shù);另一個(gè)變量表示下一層節(jié)點(diǎn)數(shù)。

class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = None class Solution:def Print(self, root):if not root:return Nonequeue = [root]toBePrinted = 1 # 表示當(dāng)前層中還沒(méi)有打印的節(jié)點(diǎn)數(shù)nextLevel = 0 # 表示下一層的節(jié)點(diǎn)數(shù)while len(queue) > 0:currentRoot = queue.pop(0)# 按空格隔開(kāi),不換行輸出print(currentRoot.val, end=" ")if currentRoot.left:queue.append(currentRoot.left)nextLevel += 1if currentRoot.right:queue.append(currentRoot.right)nextLevel += 1toBePrinted -= 1# 如果當(dāng)前層未打印的節(jié)點(diǎn)數(shù)為0,就跳轉(zhuǎn)到下一層if toBePrinted == 0:# 如果下一層沒(méi)有東西了,就不再執(zhí)行程序了if nextLevel == 0:breakprint("\n")toBePrinted = nextLevelnextLevel = 0pNode1 = TreeNode(8) pNode2 = TreeNode(6) pNode3 = TreeNode(10) pNode4 = TreeNode(5) pNode5 = TreeNode(7) pNode6 = TreeNode(9) pNode7 = TreeNode(11)pNode1.left = pNode2 pNode1.right = pNode3 pNode2.left = pNode4 pNode2.right = pNode5 pNode3.left = pNode6 pNode3.right = pNode7S = Solution() S.Print(pNode1)

總結(jié)

以上是生活随笔為你收集整理的Python剑指offer:分行从上到下打印二叉树的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。