257. Binary Tree Paths

来源:互联网 发布:java未来五年发展前景 编辑:程序博客网 时间:2024/05/22 17:17

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

思路:就是一个回溯的dfs、

代码如下(已通过leetcode)

public class Solution {
   public List<String> binaryTreePaths(TreeNode root) {
       List<String> list=new ArrayList<String>();
       if(root==null) return list;
       String s="";
       DFS(root,s,list);
       return list;
   }
   
   public void DFS(TreeNode root,String s,List<String> list) {
   
    if(root.left==null && root.right==null) {
    s=s+root.val;
    list.add(s);
    s="";
    } else {
    s=s+root.val+"->";
    if(root.left!=null) {
   
    DFS(root.left,s,list);
    }
    if(root.right!=null) {
   
    DFS(root.right,s,list);
    }
    }
   }
}

0 0
原创粉丝点击