Given a binary tree, return all root-to-leaf paths.
Given the following binary tree:
1
/
2 3
5
All root-to-leaf paths are:
[ "1->2->5", "1->3" ]
解题思路:这道题目应该就是单纯的二叉树遍历,从根节点出发,遍历左右子节点并记录遍历路径,递归调用至叶节点;
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 List<String> res = new ArrayList<String>(); 15 public List<String> binaryTreePaths(TreeNode root) { 16 // Write your code here 17 if(root != null) findPaths(root,String.valueOf(root.val)); 18 return res; 19 } 20 public void findPaths(TreeNode n,String path){ 21 if(n.left==null && n.right==null) res.add(path); 22 if(n.right!=null) findPaths(n.right,path+"->"+n.right.val); 23 if(n.left!= null) findPaths(n.left ,path+"->"+n.left.val); 24 } 25 }