Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> result = new ArrayList<String>(); binaryTreePathsFinder(root, "", result); return result; } public void binaryTreePathsFinder(TreeNode root, String path, List<String> result){ if (root == null) return ; if(root.left == null && root.right == null){ result.add(path + root.val); } else if( root.left != null && root.right != null){ path = path + root.val + "->"; binaryTreePathsFinder(root.left, path, result); binaryTreePathsFinder(root.right, path, result); } else if(root.left != null && root.right == null){ path = path + root.val + "->"; binaryTreePathsFinder(root.left, path, result); } else{ path = path + root.val + "->"; binaryTreePathsFinder(root.right, path, result); } } }
|
1 2 3 4 5 6 7 8 9 10
| public List<String> binaryTreePaths(TreeNode root) { List<String> answer = new ArrayList<String>(); if (root != null) searchBT(root, "", answer); return answer; } private void searchBT(TreeNode root, String path, List<String> answer) { if (root.left == null && root.right == null) answer.add(path + root.val); if (root.left != null) searchBT(root.left, path + root.val + "->", answer); if (root.right != null) searchBT(root.right, path + root.val + "->", answer); }
|