Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \ 2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
This is a popular interview question in LeetCode and GeeksForGeeks A collection of hundreds of interview questions and solutions are available in our blog at Interview Question Solutions
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
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* | |
* Given a binary tree, return all root-to-leaf paths. | |
* | |
* For example, given the following binary tree: | |
* | |
* 1 | |
* / \ | |
* 2 3 | |
* \ | |
* 5 | |
* All root-to-leaf paths are: | |
* | |
* ["1->2->5", "1->3"] | |
* | |
* | |
* Solution 1: | |
* 1)start from the root node and traverse down its child | |
* 2)take one branch at a time for every traversed node and add the value of the node to | |
* the path string | |
* 3)when the next child node (on left side and right side) is null, the string is complete, | |
* else we just keep on appending the value of this node to the current path | |
* | |
* | |
* @author rbaral | |
*/ | |
/** | |
* Definition for a binary tree node. public class TreeNode { int val; TreeNode | |
* left; TreeNode right; TreeNode(int x) { val = x; } } | |
*/ | |
public class BinaryTreePath { | |
public static List<String> binaryTreePaths(TreeNode root) { | |
List<String> pathList = new ArrayList<String>(); | |
if (root != null) { | |
performDFS(root, "", pathList); | |
} | |
return pathList; | |
} | |
static void performDFS(TreeNode root, String path, List<String> pathList) { | |
if (root.left == null && root.right == null) { | |
pathList.add(path + root.val); | |
} | |
if (root.left != null) { | |
performDFS(root.left, path + root.val + "->", pathList); | |
} | |
if (root.right != null) { | |
performDFS(root.right, path + root.val + "->", pathList); | |
} | |
} | |
public static void main(String args[]) { | |
} | |
} |
No comments:
Post a Comment