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

tiffanytown
6 声望2 粉丝

keep learning