Leetcode 145. Binary Tree Postorder Traversal

Problem

Given the root of a binary tree, return the postorder traversal of its nodes’ values.

Algorithm

dfs.

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        
        ans = []
        def dfs(proot):
            if not proot:
                return
            dfs(proot.left)
            dfs(proot.right)
            ans.append(proot.val)
            
        dfs(root)
        
        return ans

你可能感兴趣的:(Leetcode,解题报告,leetcode,算法,职场和发展)