Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Given a binary tree, return all root-to-leaf paths.
- Note: A leaf is a node with no children.
- Example:
- Input:
- 1
- / \
- 2 3
- \
- 5
- Output: ["1->2->5", "1->3"]
- Explanation: All root-to-leaf paths are: 1->2->5, 1->3Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- class Solution {
- public List<String> binaryTreePaths(TreeNode root) {
- List<String> result = new ArrayList<String>();
- if(root == null){
- return result;
- }
- //String path = Integer.toString(root.val);
- traverse(result, Integer.toString(root.val), root);
- return result;
- }
- private void traverse(List<String> result, String path, TreeNode currNode){
- if(currNode.left == null && currNode.right == null){
- result.add(path);
- return;
- }
- if(currNode.left != null){
- traverse(result, path + "->"+ currNode.left.val, currNode.left);
- }if(currNode.right != null){
- traverse(result, path + "->"+ currNode.right.val, currNode.right);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement