Easy-题目53:257. Binary Tree Paths

转载 2016年05月30日 20:51:35

题目原文:
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”]
题目大意:
给出一个二叉树,输出所有从根节点到叶子节点的路径。
题目分析:
遍历即可,注意每次向左右子树搜索的时候,把当前路径一直带在函数参数里面。
源码:(language:java)

public class Solution {
    List<String> res = new ArrayList<String>();    
    public List<String> binaryTreePaths(TreeNode root) {
        if(root != null) findPaths(root,String.valueOf(root.val));
        return res;
    }    
    private void findPaths(TreeNode n, String path){
        if(n.left == null && n.right == null) res.add(path);
        if(n.left != null) findPaths(n.left, path+"->"+n.left.val);
        if(n.right != null) findPaths(n.right, path+"->"+n.right.val);
    }
}

成绩:
3ms,beats 27.22%,众数3ms,47.28%.

相关文章推荐

LeetCode 257. Binary Tree Paths 递归过程保存信息

257. Binary Tree Paths Given a binary tree, return all root-to-leaf paths. For example, given...

leetcode 每日一题 257. Binary Tree Paths

给出二叉树,求所有从根到叶子节点的路径并打印 这道题可以用递归解(DFS),但是对递归理解的还是不够,并且判断条件的时候太大意了 一直RE,烦得很 后来经臭臭指点找到了原因。 ...

【LeetCode-257】Binary Tree Paths(C++)

题目要求:要求输出一个二叉树的所有从根节点到叶子节点的路径。 解题方法: 1. 可以用递归的方法实现,将根节点的左右子树所输出的两个数组合并为一个数组,并将得到的数组的每一个string元素头部加上"...

leetcode 257. Binary Tree Paths

/* leetcode 257. Binary Tree Paths Given a binary tree, return all root-to-leaf paths. For example, ...

257. Binary Tree Paths-LeetCode(树的全部路径)(第一次写树,兴奋)

第一次写有关树结构的代码,运行通过心里还是蛮开心的。 Total Accepted: 29117 Total Submissions: 113069 Difficulty: Easy Giv...

leetcode257 Binary Tree Paths

Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree:...

LeetCode题解-257-Binary Tree Paths

原题 原题链接:https://leetcode.com/problems/binary-tree-paths/ 解法概览 解法1:迭代法,后序遍历 解法2:递归法,参考了ht...

【LeetCode】257. Binary Tree Paths 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280Subject 出处:https://leetcode.com/pro...

【LeetCode】 257.Binary Tree Paths 解法的注解

257. Binary Tree Paths My Submissions Question Total Accepted: 40763 Total Submissions: 146109 D...

257. Binary Tree Paths(打印二叉树所有路径)

Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree: 1...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Easy-题目53:257. Binary Tree Paths
举报原因:
原因补充:

(最多只允许输入30个字)