144 + 145 - 二叉树的前序遍历 + 二叉树的后序遍历 - python

50 阅读1分钟

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

示例:

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

输出: [1,2,3]
输出:[3,2,1]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?


迭代法-前序遍历

class Solution(object):
    def preorderTraversal(self, root):

        if not root :return []
        
        stack = [root, ]
        res = []
        while stack:
            root = stack.pop()
            if root:
                res.append(root.val)
                if root.right:
                    stack.append(root.right)
                if root.left:
                    stack.append(root.left)
        
        return res

迭代法-后序遍历:

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        if not root: return []
        stack = [root]
        res = []
        while stack:
            node = stack.pop()
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
            res.append(node.val)

        return res[::-1]

更多可见: python - 二叉树