257. Binary Tree Paths

来源:互联网 发布:linux 守护进程脚本 编辑:程序博客网 时间:2024/05/23 01:15

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"]

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

dfs

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {   private List <String> ret = new ArrayList <String> ();    private void depDFS (String s,TreeNode root ){        if(root.left==null&&root.right==null)ret.add(s+"->"+String.valueOf(root.val));        if(root.left!=null)depDFS(s+"->"+String.valueOf(root.val),root.left);        if(root.right!=null)depDFS(s+"->"+String.valueOf(root.val),root.right);    }    public List<String> binaryTreePaths(TreeNode root) {        if(root==null)return ret;        String s = String.valueOf(root.val);        if(root.left==null&&root.right==null)ret.add(s);        if(root.left!=null)depDFS(s,root.left);        if(root.right!=null)depDFS(s,root.right);        return ret;    }}

0 0
原创粉丝点击