导航

(easy)LeetCode 257.Binary Tree Paths

Posted on 2015-08-16 12:16  骄阳照林  阅读(130)  评论(0编辑  收藏  举报

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

思想:递归
代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
       List<String> ret=new ArrayList<>();
       if(root==null) return ret;
       String s=""+root.val;
       paths(root,s,ret);
       return ret;
    }
    public void paths(TreeNode root,String s,List<String>ret){
        if(root.left==null && root.right==null){
            ret.add(s);
        }
        else{
            if(root.left!=null) paths(root.left,s+"->"+root.left.val,ret);
            if(root.right!=null) paths(root.right,s+"->"+root.right.val,ret);
        }
    }
    
}

  

运行结果: