日野弥生:勉強しよう

LeetCode 257 - 二叉树的所有路径

发表于2025年03月08日

#树 #二叉树 #字符串 #回溯 #深度优先搜索

递归解题,整体思路是先根遍历。

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        result = []
        nodeList = []
        # 列表推导式可用快速把列表变成字符串
        def listToStr():
            str_arr = '->'.join([str(x) for x in nodeList])
            result.append(str_arr)
        def binaryTreePathsIMPL(root: Optional[TreeNode]):
            #节点为空直接返回
            if not root:
                return
            # 节点不为空加入列表方便回溯
            nodeList.append(root.val)

            # 到达叶子节点后打印,同时弹出当前节点
            if not root.left and not root.right:
                listToStr()
                nodeList.pop()
                return
            
            # 递归
            binaryTreePathsIMPL(root.left)
            binaryTreePathsIMPL(root.right)

            # 完成左右子树的遍历后,弹出当前节点
            nodeList.pop()
        binaryTreePathsIMPL(root)
        return result

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/binary-tree-paths/

上一篇

LeetCode 100 - 相同的树

下一篇

LeetCode 404 - 左叶子之和