题目:

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;
}
}

二刷:

还是使用了最简单的DFS Recursive解法。更好的解法可能是stack DFS和queue BFS。

Java:

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(root.val + "");
return res;
}
List<String> left = binaryTreePaths(root.left);
List<String> right = binaryTreePaths(root.right);
for (String s : left) {
res.add(root.val + "->" + s);
}
for (String s : right) {
res.add(root.val + "->" + s);
}
return res;
}
}

三刷:

完全忘了一刷二刷是怎么写的,直接就用dfs + backtracking了。辅助方法里面用的是in-order traversal。 这里使用了一个List<Integer>来辅助计算Path,否则单独使用一个StringBuilder并不十分方便。

Java:

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<>();
List<Integer> path = new ArrayList<>();
getBinaryTreePaths(res, path, root);
return res;
} private void getBinaryTreePaths(List<String> res, List<Integer> path, TreeNode root) {
if (root == null) return;
path.add(root.val);
if (root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (int val : path) sb.append(val).append("->");
sb.setLength(sb.length() - 2);
res.add(sb.toString());
path.remove(path.size() - 1);
return;
}
getBinaryTreePaths(res, path, root.left);
getBinaryTreePaths(res, path, root.right);
path.remove(path.size() - 1);
}
}

Update:

/**
* 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<>();
binaryTreePaths(res, new ArrayList<Integer>(), root);
return res;
} private void binaryTreePaths(List<String> res, List<Integer> path, TreeNode root) {
if (root == null) return;
path.add(root.val);
if (root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (int val : path) sb.append(val).append("->");
sb.setLength(sb.length() - 2);
res.add(sb.toString());
path.remove(path.size() - 1);
return;
}
binaryTreePaths(res, path, root.left);
binaryTreePaths(res, path, root.right);
path.remove(path.size() - 1);
}
}

写在一个方法里,仿照一刷二刷的dfs:

这里每次递归都要创建新的ArrayList,并且左右子树都要计算,空间复杂度会比较高。怎么计算清楚,留给下一次了。

/**
* 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)); List<String> left = binaryTreePaths(root.left);
for (String leftPath :left) res.add(root.val + "->" + leftPath); List<String> right = binaryTreePaths(root.right);
for (String rightPath :right) res.add(root.val + "->" + rightPath); return res;
}
}

Reference:

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

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

https://leetcode.com/discuss/67749/bfs-with-two-queue-java-solution

257. Binary Tree Paths的更多相关文章

  1. &lt;LeetCode OJ&gt; 257. Binary Tree Paths

    257. Binary Tree Paths Total Accepted: 29282 Total Submissions: 113527 Difficulty: Easy Given a bina ...

  2. 【LeetCode】257. Binary Tree Paths

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

  3. Leetcode 257. Binary Tree Paths

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

  4. (easy)LeetCode 257.Binary Tree Paths

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

  5. Java [Leetcode 257]Binary Tree Paths

    题目描述: Given a binary tree, return all root-to-leaf paths. For example, given the following binary tr ...

  6. LeetCode OJ 257. Binary Tree Paths

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

  7. LeetCode 257. Binary Tree Paths (二叉树路径)

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

  8. 【一天一道LeetCode】#257. Binary Tree Paths

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  9. [LeetCode&Python] Problem 257. Binary Tree Paths

    Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example ...

随机推荐

  1. 最新区分兼容IE6/IE7/IE8/IE9/FF的CSS HACK写法和Css if hack条件语法操作说明

    自从安装了IE8.0正式版本!木头 就对基本的几个 CSS HACK的做一下归纳!希望对网页前端布局DIV+CSS的实施者有所帮助! 本文就主要以:IE6+IE7+IE8+IE9+FF为主要研究对象 ...

  2. Delphi XE5教程12:注释和编译器指示字

    内容源自Delphi XE5 UPDATE 2官方帮助<Delphi Reference>,本人水平有限,欢迎各位高人修正相关错误!也欢迎各位加入到Delphi学习资料汉化中来,有兴趣者可 ...

  3. SQLServer处理亿万级别的数据的优化措施

    如何在SQLServer中处理亿万级别的数据(历史数据),可以按以下方面进行: 去掉表的所有索引 用SqlBulkCopy进行插入 分表或者分区,减少每个表的数据总量 在某个表完全写完之后再建立索引 ...

  4. openerp学习笔记 错误、警告、提示、确认信息显示

    1.检查业务逻辑中的错误,终止代码执行,显示错误或警告信息: raise osv.except_osv(_('Error!'), _('Error Message.')) 示例代码: #删除当前销售单 ...

  5. mysql学习笔记之基础篇

    数据库学习之基础篇 ① 开放数据库互连(Open Database Connectivity,ODBC ② 结构化查询语言(Structured Query Language) ③ 进入mysql:M ...

  6. 64bit Ubuntu, Android AAPT, R.java

    Ubuntu 13.10 aapt: error while loading shared libraries: libstdc++.so.6: cannot open shared object f ...

  7. Interview-Increasing Sequence with Length 3.

    Given an array, determine whether there are three elements A[i],A[j],A[k], such that A[i]<A[j]< ...

  8. C+= concurrent_queue 线程安全测试

    更推荐使用:http://www.boost.org/doc/libs/1_56_0/doc/html/boost/lockfree/queue.html #include <include/t ...

  9. Codeforces Round #130 (Div. 2) A. Dubstep

    题目链接: http://codeforces.com/problemset/problem/208/A A. Dubstep time limit per test:2 secondsmemory ...

  10. java 使用 comet4j 主动向客户端推送信息 简单例子

    [背景] 今天,一个前端的师弟问我怎样做实时聊天窗口,我毫不犹豫地说:在前台定时访问服务端呀!师弟默默地百度了一番,最后告诉我,有一种技术是后服务端动推送信息给客户端的,这种技术的名字叫comet,我 ...