Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 12, 2017 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/b65b4e28346b2b755b15909d49f5f3f5 to your computer and use it in GitHub Desktop.
Save InterviewBytes/b65b4e28346b2b755b15909d49f5f3f5 to your computer and use it in GitHub Desktop.
Binary Tree Paths
package com.interviewbytes.trees;
import java.util.ArrayList;
import java.util.List;
public class BinaryTreePaths {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<>();
helper(root, "", paths);
return paths;
}
private void helper(TreeNode node, String path, List<String> paths) {
if (node == null) return;
path += path.isEmpty() ? node.val : "->" + node.val;
if (node.left == null && node.right == null) paths.add(path);
helper(node.left, path, paths);
helper(node.right, path, paths);
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment