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

257. Binary Tree Paths

时间:2015-12-03 07:12:59      阅读:181      评论: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"]

链接: http://leetcode.com/problems/binary-tree-paths/

题解:

求Binary Tree所有路径。用Recursive解法会比较容易。逻辑是,假如为current root为leaf node,则在res中加入该节点,返回。否则,递归求解,在左子树和右子树每一个结果中,在String前面insert  root.val + "->"。

Time Complexity - O(n), Space Complexity - O(n)

/**
 * 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> res = new ArrayList<>();
        if(root == null)
            return res;
        if(root.left == null && root.right == null) {
            res.add(String.valueOf(root.val));
        } else {
            for(String s : binaryTreePaths(root.left)) {
                res.add(String.valueOf(root.val) + "->" + s);
            } 
            for(String s : binaryTreePaths(root.right)) {
                res.add(String.valueOf(root.val) + "->" + s);
            } 
        }
            
        return res;
    }
}

 

Reference:

https://leetcode.com/discuss/65362/my-concise-java-dfs-solution

https://leetcode.com/discuss/55451/clean-solution-accepted-without-helper-recursive-function

https://leetcode.com/discuss/52072/accepted-java-simple-solution-in-8-lines

https://leetcode.com/discuss/52020/5-lines-recursive-python

 

257. Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/5014959.html

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