-
-
Save InterviewBytes/b65b4e28346b2b755b15909d49f5f3f5 to your computer and use it in GitHub Desktop.
Binary Tree Paths
This file contains 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
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); | |
} | |
} |
This file contains 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
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