作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/



题目地址:https://leetcode.com/problems/binary-tree-paths/#/description

题目描述

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
/ \
2 3
\
5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3

题目大意

但引出所有的从根节点到叶子节点的路径。

解题方法

递归

把二叉树的从根节点到叶子节点的每条路径都打印出来,实用的方法就是很简单的递归调用。如果是叶子就把这个路径保存到list中,如果不是叶子就把这个节点的值放入到path中,然后再继续调用,直到达到叶子节点为止。

我用StringBuilder的结果会糅杂在一起,就不能用,也没想明白为什么= =

java版本:

/**
* 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> ans = new ArrayList<String>();
if(root != null){
searchNode(root, "", ans);
}
return ans;
} public void searchNode(TreeNode root, String path, List<String> ans){
if(root.left == null && root.right == null){
ans.add(path + root.val);
}
if(root.left != null){
searchNode(root.left, path + root.val + "->", ans);
}
if(root.right != null){
searchNode(root.right, path + root.val + "->", ans);
}
}
}

===========二刷

把path作为字符串,res作为数组保存字符串。一般递归都可以这么写的。

python版本:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
res = []
self.dfs(root, res, '' + str(root.val))
return res def dfs(self, root, res, path):
if root.left == None and root.right == None:
res.append(path)
if root.left != None:
self.dfs(root.left, res, path + '->' + str(root.left.val))
if root.right != None:
self.dfs(root.right, res, path + '->' + str(root.right.val))

迭代

使用迭代的话,大家都知道需要用一个栈,那么感觉就是个模板题了,而且和上面的递归做法基本是一样的了。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
stack = []
res = []
stack.append((root, str(root.val)))
while stack:
node, path = stack.pop()
if not node.left and not node.right:
res.append(path)
if node.left:
stack.append((node.left, path + "->" + str(node.left.val)))
if node.right:
stack.append((node.right, path + "->" + str(node.right.val)))
return res

日期

2017 年 5 月 6 日
2018 年 2 月 25 日
2018 年 11 月 19 日 —— 周一又开始了

【LeetCode】257. Binary Tree Paths 解题报告(java & python)的更多相关文章

  1. Java [Leetcode 257]Binary Tree Paths

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

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

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

  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. 【LeetCode】919. Complete Binary Tree Inserter 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址: https://leetcode. ...

  5. 【LeetCode】814. Binary Tree Pruning 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 后序遍历 日期 题目地址:https://leetc ...

  6. Leetcode 257. Binary Tree Paths

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

  7. (easy)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二叉树路径

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

  9. LeetCode 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. 【Python小试】将核酸序列翻译成氨基酸序列

    三联密码表 gencode = { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT' ...

  2. PHP-FPM运行状态的实时查看及监控详解

    https://www.jb51.net/article/97640.htm https://blog.csdn.net/Dr_cokiy/article/details/105580758

  3. C# 设计模式(1)——简单工厂模式、工厂模式、抽象工厂模式

    1.前言 上一篇写了设计模式原则有助于我们开发程序的时候能写出高质量的代码(牵一发而不动全身),这个系列还是做个笔记温习一下各种设计模式,下面就看看简单工厂模式.工厂模式.抽象工厂模式. 2.简单工厂 ...

  4. Hive(三)【DDL 数据定义】

    目录 一.DDL数据定义 1.库的DDL 1.1创建数据库 1.2查询数据库 1.3查看数据库详情 1.4切换数据库 1.5修改数据库 1.6删除数据库 2.表的DDL 2.1创建表 2.2管理表(内 ...

  5. SpringBoot-RestTemplate测试Controller

    1.功能测试类 package com.imooc.controller; import java.io.IOException; import java.math.BigDecimal; impor ...

  6. GO 通过进程号输出运行运行信息

    操作系统应用可以使用PID来查找关于进程本身的信息.当进程失败时获取到的PID就非常有价值,这样就可以使用PID跟踪整个系统中的系统日志,如/var/log/messages./var/log/sys ...

  7. App内容分享

    1.发送文本内容 发送简单的数据到其他应用,比如社交分分享的内容,意图允许用户快速而方便的共享信息. //分享简单的文本内容 public void btnShareText(View view) { ...

  8. 神器Tampermonkey的安装使用

    Tampermonkey是一款基于浏览器的神奇插件,在国内称为油猴,开发者可以在上面开发满足自己需求的各类浏览器应用脚本.不过经过全球各地无数开发者数年的积累现在其官网已经有一大把的优秀的现成脚本,完 ...

  9. 【Java基础】ExecutorService的使用

    ExecutorService是java中的一个异步执行的框架,通过使用ExecutorService可以方便的创建多线程执行环境. 本文将会详细的讲解ExecutorService的具体使用. 创建 ...

  10. Mysql中replace与replace into的用法讲解

    Mysql replace与replace into都是经常会用到的功能:replace其实是做了一次update操作,而不是先delete再insert:而replace into其实与insert ...