Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.code
For example, given the following binary tree:遞歸
1 / \ 2 3 \ 5
All root-to-leaf paths are:io
["1->2->5", "1->3"]
1.解題思路class
求根節點到葉子節點的路徑集合,採用深度搜索,利用遞歸實現。List
2.代碼搜索
public class Solution { List<String> res=new ArrayList<String>(); public List<String> binaryTreePaths(TreeNode root) { helper(root,new String()); return res; } private void helper(TreeNode root,String pre){ if(root==null) return; if(root.left==null&&root.right==null){ res.add(pre+root.val); return; } helper(root.left,pre+root.val+"->"); helper(root.right,pre+root.val+"->"); } }