1. 程式人生 > >【Leetcode_總結】145. 二叉樹的後序遍歷 - python

【Leetcode_總結】145. 二叉樹的後序遍歷 - python

Q:

給定一個二叉樹,返回它的 後序 遍歷。

示例:

輸入: [1,null,2,3]  
   1
    \
     2
    /
   3 

輸出: [3,2,1]

進階: 遞迴演算法很簡單,你可以通過迭代演算法完成嗎?


連結:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/description/

思路:遞迴 後續遍歷

程式碼:

# 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):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root == None:
            return []
        else:
            res = []
            self.later_digui(root, res)
        return res
    
    def later_digui(self,root,res):
        if root == None:
            return
        self.later_digui(root.left,res)
        self.later_digui(root.right,res)
        res.append(root.val)