Binary Tree Paths(lintcode 480)
Description
Given a binary tree, return all root-to-leaf paths.
Example
Given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[
"1->2->5",
"1->3"
]
Interface
/**
* 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) {
// Write your code here
}
}
Solution
/**
* 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
*/
private List<String> result = new ArrayList<String>();
public List<String> binaryTreePaths(TreeNode root) {
// Write your code here
traverse(root, "");
return result;
}
private void traverse(TreeNode root, String path) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
path += root.val;
result.add(path);
return;
}
path += root.val;
traverse(root.left, path + "->");
traverse(root.right, path + "->");
}
}