leedcode-二叉树的所有路径

迭代法-深度优先搜索(栈)

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        if not root:
            return []  # 如果根节点为空,直接返回空列表
        
        stack = [(root, str(root.val))]  # 初始化栈,栈中存储的是节点和对应的路径
        res = []  # 用于存储所有路径
        
        while stack:
            cur, path = stack.pop()  # 弹出栈顶节点及其对应的路径
            
            if not cur.left and not cur.right:  # 如果当前节点是叶子节点
                res.append(path)  # 将当前路径添加到结果列表中
            
            if cur.right:  # 如果右子节点存在,则将右子节点及路径入栈
                stack.append((cur.right, path + "->" + str(cur.right.val)))
            
            if cur.left:  # 如果左子节点存在,则将左子节点及路径入栈
                stack.append((cur.left, path + "->" + str(cur.left.val)))
        
        return res  # 返回所有路径列表

 递归:

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []  # 用于存储所有路径
        path = ""  # 当前路径字符串
        self.getPath(res, path, root)  # 调用递归函数获取所有路径
        return res  # 返回所有路径列表
    
    def getPath(self, res, path, root):
        if not root:
            return  # 如果当前节点为空,直接返回
        
        path += str(root.val)  # 将当前节点的值添加到路径字符串中
        
        if not root.left and not root.right:  # 如果当前节点是叶子节点
            res.append(path)  # 将当前路径添加到结果列表中
        else:
            path += "->"  # 如果当前节点不是叶子节点,则在路径字符串后添加箭头符号
        
            self.getPath(res, path, root.left)  # 递归遍历左子树
            self.getPath(res, path, root.right)  # 递归遍历右子树

 

posted @ 2024-03-23 18:41  Junior_bond  阅读(11)  评论(0)    收藏  举报