Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 14, 2017 01:01
Show Gist options
  • Select an option

  • Save cixuuz/c172b271cf8a56cc1224320a497cec1a to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/c172b271cf8a56cc1224320a497cec1a to your computer and use it in GitHub Desktop.
[257. Binary Tree Paths] #leetcode
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);
}
}
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