演算法導論p138 10.4-2
題目要求:
給定乙個n節點的二叉樹,寫出乙個o(n)時間的遞迴過程,將概述每個節點的關鍵字輸出。
利用python3來實現。
''' 18
/\12 10
/\ /\
7 4 2 21/5
'''##treenode定義
class
treenode
:def
__init__
(self, x)
: self.val = x
self.left =
none
self.right =
none
def__str__
(self)
:return f'(root: -[left: , right: ])'
##遞迴遍歷
from typing import list
from define.treenode import treenode
class
solution
:# 前序遍歷
defgetallnodes0
(self, root=treenode)
-> list[
int]:if
not self:
return
list()
reslist =
list()
if root:
if root.left:
reslist.extend(solution.getallnodes0(self, root.left)
)if root.right:
reslist.extend(solution.getallnodes0(self, root.right)
)return reslist
# 中序遍歷
defgetallnodes1
(self, root=treenode)
-> list[
int]:if
not self:
return
list()
reslist =
list()
if root:
if root.left:
reslist.extend(solution.getallnodes1(self, root.left)
)if root.right:
reslist.extend(solution.getallnodes1(self, root.right)
)return reslist
# 後序遍歷
defgetallnodes2
(self, root=treenode)
-> list[
int]:if
not self:
return
list()
reslist =
list()
if root:
if root.left:
reslist.extend(solution.getallnodes2(self, root.left)
)if root.right:
reslist.extend(solution.getallnodes2(self, root.right)
)return reslist
if __name__ ==
'__main__'
: root = treenode(18)
root.left = treenode(12)
root.right = treenode(10)
root.left.left = treenode(7)
root.left.right = treenode(4)
root.right.left = treenode(2)
root.right.right = treenode(21)
root.left.right.left = treenode(5)
print
(root)
print
(solution.getallnodes0(self=root, root=root)
)# [18, 12, 7, 4, 5, 10, 2, 21]
print
(solution.getallnodes1(self=root, root=root)
)# [7, 12, 5, 4, 18, 2, 10, 21]
print
(solution.getallnodes2(self=root, root=root)
)# [7, 5, 4, 12, 2, 21, 10, 18]
還有另外一道題,10.4-3,使用非遞迴,用棧作輔助,輸出二叉樹的全部節點。
def
getallnodesbystack
(self, root=treenode)
-> list[
int]:if
not self:
return
stack, reslist =
list()
,[]while stack:
node = stack.pop(
)if node.left:
if node.right:
return reslist
使用佇列實現二叉樹非遞迴展示,廣度優先:
def
getallnodesbyqueue
(self, root=treenode)
-> list[
int]:if
not self:
return
queue, reslist = collections.deque(),
while queue:
node = queue.popleft(
)if node.left:
if node.right:
return reslist
每日一題力扣222 完全二叉樹節點的個數
給你一棵 完全二叉樹 的根節點root,求出該樹的節點個數。完全二叉樹 的定義如下 在完全二叉樹中,除了最底層節點可能沒填滿外,其餘每層節點數都達到最大值,並且最下面一層的節點都集中在該層最左邊的若干位置。若最底層為第h層,則該層包含1 2h個節點。class solution def countn...
每日一題 35二叉樹前序遍歷
給定乙個二叉樹,返回它的前序遍歷。示例 輸入 1,null,2,3 1 2 3 輸出 1,2,3 首先二叉樹的遞迴遍歷 private void preorder treenode root,list res 第二 二叉樹的非遞迴 使用棧來儲存節點 效率不是很高 definition for a b...
每日一題 32 二叉樹的後序遍歷
給定乙個二叉樹,返回它的 後序 遍歷。示例 輸入 1,null,2,3 1 2 3 輸出 3,2,1 高階 遞迴演算法很簡單,你可以通過迭代演算法完成嗎?遞迴演算法 解答 definition for a binary tree node.struct treenode class solution...