二叉树的前序遍历
思想:主要会用到数据结构 stack, 不说废话,直接上代码;
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
stack = []
result = []
stack.append(root)
while(len(stack) > 0):
node = stack.pop()
result.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
二叉树的中序遍历
# Definition for a binary tree no

本文介绍了如何使用Python通过迭代方法实现二叉树的前序、中序和后序遍历,详细阐述了遍历过程并提供了相应的代码实现。
最低0.47元/天 解锁文章
441

被折叠的 条评论
为什么被折叠?



