码迷,mamicode.com
首页 > 其他好文 > 详细

(easy)LeetCode 257.Binary Tree Paths

时间:2015-08-16 13:41:29      阅读:422      评论:0      收藏: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);
        }
    }
    
}

  

运行结果:

      技术分享

(easy)LeetCode 257.Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/mlz-2019/p/4734005.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!