Skip to content

Instantly share code, notes, and snippets.

@thanlau
Created April 20, 2017 22:14
Show Gist options
  • Save thanlau/b454ba3229c3ff4f7926d02ac3d3db5b to your computer and use it in GitHub Desktop.
Save thanlau/b454ba3229c3ff4f7926d02ac3d3db5b to your computer and use it in GitHub Desktop.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
public List<String> binaryTreePaths(TreeNode root) {
/**思路
* DFS。一层一层往下走并且更新path,
* 如果发现已经到leaf了,那么把整个path加到result里去。*/
//存储最终结果
List<String> result = new ArrayList<>();
if (root == null) {
return result;
}
helper(result, "" + root.val, root);
return result;
}
public void helper(List<String> result, String path, TreeNode root) {
if (root.left == null && root.right == null) {
result.add(path);
return;
}
if (root.left != null) {
helper(result, path + "->" + root.left.val, root.left);
}
if (root.right != null) {
helper(result, path + "->" + root.right.val, root.right);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment