Python | Leetcode Python题解之第145题二叉树的后序遍历

题目:

题解:

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        def addPath(node: TreeNode):
            count = 0
            while node:
                count += 1
                res.append(node.val)
                node = node.right
            i, j = len(res) - count, len(res) - 1
            while i < j:
                res[i], res[j] = res[j], res[i]
                i += 1
                j -= 1
        
        if not root:
            return list()
        
        res = list()
        p1 = root

        while p1:
            p2 = p1.left
            if p2:
                while p2.right and p2.right != p1:
                    p2 = p2.right
                if not p2.right:
                    p2.right = p1
                    p1 = p1.left
                    continue
                else:
                    p2.right = None
                    addPath(p1.left)
            p1 = p1.right
        
        addPath(root)
        return res

最近更新

  1. TCP协议是安全的吗?

    2024-06-16 03:32:06       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-16 03:32:06       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-16 03:32:06       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-16 03:32:06       20 阅读

热门阅读

  1. 【LeetCode 12】整数转罗马数字

    2024-06-16 03:32:06       8 阅读
  2. c++处理字符串

    2024-06-16 03:32:06       9 阅读
  3. *args和**kwargs这个在python中的意思

    2024-06-16 03:32:06       9 阅读
  4. Qt事件处理和传递流程

    2024-06-16 03:32:06       6 阅读
  5. springboot事务管理的机制是什么

    2024-06-16 03:32:06       4 阅读
  6. datalist 是什么?

    2024-06-16 03:32:06       5 阅读