标签:
Given a binary tree, return all root-to-leaf paths.
Given the following binary tree:
1 1 2 / 3 2 3 4 5 5
All root-to-leaf paths are:
1 [ 2 "1->2->5", 3 "1->3" 4 ]
As mentioned in the problem we want to get all root-to-leaf paths. Because all the paths need to be found and I was considering recursively finding this could be very efficently due to reducing the possibility that missing some case.
To recursively do it, three things need to be considered:
1. What is the relationship of problem of this this tree and its two subtrees?
2. Is the problem size reducing?
3. What is the base case?
So
1. the traversing done for this tree is the traversing of this node plus left tree and right tree. We need to put the node‘s value to a string and when the traverse is reaching the leaves and/or null values we should return.
2. yes
3. Base case is the tree is only one node or null;
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param root the root of the binary tree 15 * @return all root-to-leaf paths 16 */ 17 public List<String> binaryTreePaths(TreeNode root) { 18 // Write your code here 19 List<String> result = new ArrayList<String>(); 20 if (root == null) { 21 return result; 22 } 23 traverse(root,String.valueOf(root.val),result); 24 return result; 25 } 26 27 public void traverse(TreeNode root, String path, List<String> lists) { 28 if (root == null) { 29 return; 30 } 31 if (root.left == null && root.right == null) { 32 lists.add(path); 33 return; 34 } 35 if (root.left != null) { 36 traverse(root.left,path+"->"+String.valueOf(root.left.val),lists); 37 } 38 if (root.right != null) { 39 traverse(root.right,path+"->"+String.valueOf(root.right.val),lists); 40 } 41 } 42 }
The trick for this problem is that the string is used to store the current path values and the adding new node values should be done in the parameters in the function calls of the left and right subtrees. This is not what I was expected because it is confused to think things together but it could be something new to learn.
标签:
原文地址:http://www.cnblogs.com/ly91417/p/5747905.html