Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree:
1 / \2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
1.解题思路
求根节点到叶子节点的路径集合,采用深度搜索,利用递归实现。
2.代码
public class Solution { Listres=new ArrayList (); public List 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+"->"); }}