美文网首页
2023-02-28 二叉树遍历.递归概念的理解

2023-02-28 二叉树遍历.递归概念的理解

作者: 远方的飞鱼 | 来源:发表于2023-02-27 12:22 被阅读0次

递归的写法: 三部分

1.确定递归函数的返回值和参数
2.终止条件
3.确定单层递归的逻辑

二叉树遍历两种方式: 1.递归方式 2.迭代方式

前序遍历-递归-LC144_二叉树的前序遍历

class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
# 保存结果
result = []

    def traversal(root: TreeNode):
        if root == None:
            return
        result.append(root.val) # 前序
        traversal(root.left)    # 左
        traversal(root.right)   # 右

    traversal(root)
    return result

中序遍历-递归-LC94_二叉树的中序遍历

class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
result = []

    def traversal(root: TreeNode):
        if root == None:
            return
        traversal(root.left)    # 左
        result.append(root.val) # 中序
        traversal(root.right)   # 右

    traversal(root)
    return result

后序遍历-递归-LC145_二叉树的后序遍历

class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
result = []

    def traversal(root: TreeNode):
        if root == None:
            return
        traversal(root.left)    # 左
        traversal(root.right)   # 右
        result.append(root.val) # 后序

    traversal(root)
    return result

相关文章

网友评论

      本文标题:2023-02-28 二叉树遍历.递归概念的理解

      本文链接:https://www.haomeiwen.com/subject/femhldtx.html