? ? ? ?打印二叉樹最右側(cè)節(jié)點(diǎn)其實(shí)是改自二叉樹的層次遍歷,多了一步,即輸出每一層的末尾節(jié)點(diǎn)。如下題,輸出最右側(cè)節(jié)點(diǎn)結(jié)果應(yīng)為 [3,20,7]。
首先看二叉樹的層次遍歷,使用隊(duì)列(queue)來存儲二叉樹的節(jié)點(diǎn),
具體代碼層次遍歷實(shí)現(xiàn):
def levelOrder(self, root: TreeNode) -> List[List[int]]:
list = []
if root is None:return list
queue = [root]
while queue:
cur = []
for i in range(len(queue)):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
cur.append(node.val)
list.append(cur)
return list
?打印出二叉樹最右側(cè)節(jié)點(diǎn):
# 打印二叉樹最右節(jié)點(diǎn)
def printRightNode(self, root):
queue = [root]
list = []
while queue:
res = []
# 控制二叉樹每層的節(jié)點(diǎn)
for i in range(len(queue)):
node = queue.pop(0)
if node.lchild:
queue.append(node.lchild)
if node.rchild:
queue.append(node.rchild)
res.append(node.key)
list.append(res)
ans = []
for i in list:
# 取每層最后一個節(jié)點(diǎn)即為最右節(jié)點(diǎn)
ans.append(i[-1])
print(ans)
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
