日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

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

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

這道題和前面一道題十分類似,也可以用一個隊列來保存要打印的節(jié)點。
為了把二叉樹的每一行單獨打印到一行里,我們需要兩個變量:
一個變量表示當前層中還沒有打印的節(jié)點數(shù);另一個變量表示下一層節(jié)點數(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 # 表示當前層中還沒有打印的節(jié)點數(shù)nextLevel = 0 # 表示下一層的節(jié)點數(shù)while len(queue) > 0:currentRoot = queue.pop(0)# 按空格隔開,不換行輸出print(currentRoot.val, end=" ")if currentRoot.left:queue.append(currentRoot.left)nextLevel += 1if currentRoot.right:queue.append(currentRoot.right)nextLevel += 1toBePrinted -= 1# 如果當前層未打印的節(jié)點數(shù)為0,就跳轉到下一層if toBePrinted == 0:# 如果下一層沒有東西了,就不再執(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)

總結

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

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