迭代遍历二叉树
中序遍历
class Solution:
def inorderTraversal(self
, root
: TreeNode
) -> List
[int]:
res
= []
stack
= []
cur
= root
while stack
or cur
:
while cur
:
stack
.append
(cur
)
cur
= cur
.left
cur
= stack
.pop
()
res
.append
(cur
.val
)
cur
= cur
.right
return res
前序遍历
class Solution:
def preorderTraversal(self
, root
: TreeNode
) -> List
[int]:
res
= []
stack
= []
cur
= root
while stack
or cur
:
while cur
:
res
.append
(cur
.val
)
stack
.append
(cur
)
cur
= cur
.left
cur
= stack
.pop
()
cur
= cur
.right
return res
后序遍历
class Solution:
def postorderTraversal(self
, root
: TreeNode
) -> List
[int]:
res
= []
stack
= []
cur
= root
while stack
or cur
:
while cur
:
res
.append
(cur
.val
)
stack
.append
(cur
)
cur
= cur
.right
cur
= stack
.pop
()
cur
= cur
.left
return res
[::-1]
递归遍历
class Solution:
def preorderTraversal(self
, root
: TreeNode
) -> List
[int]:
def dfs(cur
):
if not cur
:
return
res
.append
(cur
.val
)
dfs
(cur
.left
)
dfs
(cur
.right
)
res
= []
dfs
(root
)
return res
层序遍历
class Solution:
def levelOrder(self
, root
: TreeNode
) -> List
[List
[int]]:
if not root
:
return []
queue
, res
= [root
], []
while queue
:
n
= len(queue
)
tmp
= []
for _
in range(n
):
node
= queue
.pop
(0)
tmp
.append
(node
.val
)
if node
.left
:
queue
.append
(node
.left
)
if node
.right
:
queue
.append
(node
.right
)
res
.append
(tmp
)
return res
转载请注明原文地址:https://tech.qufami.com/read-9858.html