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+"->"); } }