Last active
August 14, 2017 01:01
-
-
Save cixuuz/c172b271cf8a56cc1224320a497cec1a to your computer and use it in GitHub Desktop.
[257. Binary Tree Paths] #leetcode
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
| public class Solution { | |
| public List<String> binaryTreePaths(TreeNode root) { | |
| List<String> res = new ArrayList<String>(); | |
| if (root != null) dfs(root, "", res); | |
| return res; | |
| } | |
| private void dfs(TreeNode root, String path, List<String> res) { | |
| if (root.left == null && root.right == null) res.add(path + root.val); | |
| if (root.left != null) dfs(root.left, path+root.val+"->", res); | |
| if (root.right != null) dfs(root.right, path+root.val+"->", res); | |
| } | |
| } |
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
| class Solution(object): | |
| res = [] | |
| def binaryTreePaths(self, root): | |
| """ | |
| :type root: TreeNode | |
| :rtype: List[str] | |
| """ | |
| if not root: | |
| return self.res | |
| self.dfs(root, "") | |
| return self.res | |
| def dfs(self, root, tmp): | |
| if root.left == None and root.right == None: | |
| self.res.append(tmp + str(root.val)) | |
| return | |
| if root.left != None: | |
| self.dfs(root.left, tmp + str(root.val) + '->') | |
| if root.right != None: | |
| self.dfs(root.right, tmp + str(root.val) + '->') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment