题目:

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. jqueryGrid 内置的onclickSubmit afterSubmit

    $(document).ready(function() { $('#jpgCustomers').jqGrid({ //url from wich data should be requested ...

  2. IIS6下, web.config配置为targetFramework="4.0"时出404错误

    打开IIS管理器,在"Web 服务扩展" 中 将ASP.NET v4.0设置为允许就好了.这个选项默认是禁止的.

  3. Python开发【第一篇】Python模块中特殊变量

    模块中特殊变量 生产环境中,常用的就是__name__和__file__ __doc__ __package__ __cached__ __name__ __file__ 一. __doc__  #获 ...

  4. IOS UIWebView截获html并修改便签内容,宽度自适应

    需求:混合应用UIWebView打开html后,UIWebView有左右滚动条,要去掉左右滚动效果:  方法:通过js截获UIWebView中的html,然后修改html标签内容:  实例代码:  服 ...

  5. IOS 基于APNS消息推送原理与实现(JAVA后台)

    Push的原理: Push 的工作机制可以简单的概括为下图 图中,Provider是指某个iPhone软件的Push服务器,这篇文章我将使用.net作为Provider. APNS 是Apple Pu ...

  6. 【个人笔记】002-PHP基础-01-PHP快速入门-02-PHP语言相关介绍输

    002-PHP基础-01-PHP快速入门 02-PHP语言相关介绍 1.PHP是什么 Hypertext Preprocessor超文本预处理器 是一种通用开源脚本语言 Personal Home P ...

  7. cocos3.2版本中的一些新特性

    1.设置屏幕分辨率的大小,需要手动添加: 2.去掉了所有CC开头的命名: 3.所有的单例(以前是采用shared开头方法),全部改为getInstance(); 4.cocos3.x以上的版本支持C+ ...

  8. C++(MFC)

    C++(MFC) 1.关联变量(与控件关联): (1)一组单选按钮:需要将第一个单选按钮的Group选项设为true,则单选按钮就为一组(组框为标示作用).选中第一个则为0,第二个为1,依次类推(P2 ...

  9. Java工程转换为Maven工程-b

    1. 前言 在开发中经常要建立一个Maven的子工程,对于没有模板的同学来说从Java工程来转换也是一个不错的选择.本文就如何从一个Java工程创建一个Maven工程做了一个介绍,相信对于将一个Jav ...

  10. Discuz!NT3.6与网站整合(操作用户信息)解决方案

    因为网站要加个论坛,所以就用到了Discuz!NT3.6. 可惜目前官方论坛已经关闭,只有3.6版本的有源码,3.9的没有源码,不好操作,下载地址: http://download.comsenz.c ...