Leetcode练习(Python):栈类:第145题:二叉树的后序遍历:给定一个二叉树,返回它的 后序 遍历。

题目:

二叉树的后序遍历:给定一个二叉树,返回它的 后序 遍历。

思路:

递归大法好,之后补充使用栈来实现的。

程序1:递归实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        result = []
        def postorder(root):
            if root == None:
                return result
            postorder(root.left)
            postorder(root.right)
            result.append(root.val)
        postorder(root)
        return result

  

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12896638.html