美文网首页
257. Binary Tree Paths

257. Binary Tree Paths

作者: 15plus | 来源:发表于2019-08-28 23:55 被阅读0次

    原题链接:https://leetcode.com/problems/binary-tree-paths/

    两种做法,iterative or recursive. 遍历的做法更快一些也更简单。

    def binaryTreePaths(self, root: TreeNode) -> List[str]:
            self.out = []
            if not root:
                return self.out 
            
            level = [(root, str(root.val))]
            
            while level:
                node, path = level.pop()
                if not node.left and not node.right:
                    self.out.append(path)
                if node.left:
                    level.append((node.left, path+'->'+str(node.left.val)))
                if node.right:
                    level.append((node.right, path+'->'+str(node.right.val)))
                                
            return self.out
    

    相关文章

      网友评论

          本文标题:257. Binary Tree Paths

          本文链接:https://www.haomeiwen.com/subject/wepmectx.html