Binary Tree Paths

update Jun 28, 2017

leetcodearrow-up-right

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"]

分析

这道题目应该很经典,要输出所有的path,我们就需要在每层recursion中传入当前node之前的路径,也就是path。明白了这一点之后,这个问题几乎就变成了简单的dfs或者bfs。在这里,我记录三种实现,分别是recursive dfs,dfs with stack and bfs with queue。

Recursive DFS

Python Code:

DFS with Stack

相当于是一个 iterative 的 preorder traversal,但是用stack记录另一个变量:path。那么对于每个刚出stack的node来说,我们可以用它的左右孩子和他的path继续向下遍历。

Python Code:

Java Code

BFS with Queue

Python code:

update Jul 14, 2017 14:17

更新:九章算法中的思路

学习了九章,他们强调对于这类题目有两种思路,分别是traverse法和分治法前者比较类似之前的第一种python实现,利用全局变量res记录paths,然后随着遍历逐个node更新path,当走到leaf的时候把path加入res。后者则是利用同一个问题对于左右子树的结论去推导最终结论。对于这道题,先得到左右子树所有的paths,然后在他们前面加上当前node.val(用for loop)。

java 实现:

C++ 实现: