Last active
September 16, 2018 19:59
-
-
Save yokolet/e4d3cec79f9d7472d573fe2abd313943 to your computer and use it in GitHub Desktop.
Binary Tree Paths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Description: | |
| Given a binary tree, return all root-to-leaf paths. A leaf is a node with no children. | |
| Example: | |
| Input: | |
| 1 | |
| / \ | |
| 2 3 | |
| \ | |
| 5 | |
| Output: ["1->2->5", "1->3"] | |
| """ | |
| class TreeNode: | |
| def __init__(self, x): | |
| self.val = x | |
| self.left = None | |
| self.right = None | |
| def binaryTreePaths(root): | |
| """ | |
| :type root: TreeNode | |
| :rtype: List[str] | |
| """ | |
| def walk(root, path, result): | |
| path += str(root.val) | |
| if not root.left and not root.right: | |
| result.append(path) | |
| if root.left: | |
| walk(root.left, path+'->', result) | |
| if root.right: | |
| walk(root.right, path+'->', result) | |
| result = [] | |
| if not root: return result | |
| walk(root, '', result) | |
| return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment