Easy-题目53:257. Binary Tree Paths

题目原文:
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
上一篇Easy-题目52:14. Longest Common Prefix
下一篇Easy-题目54:234. Palindrome Linked List
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭