Binary Tree Path

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

这道题看起来不难,但是还是有一些地方要注意的

1. 判断条件应该是当root.left == null && root.right == null 也就是是leaf的时候path加入list。 

如果你在if root == null的时候就加入list, 你会把那些通往null的pat也加进来。


2. List可以declare globally,然后DFS function modify it。 或者define locally,当一个参数传给DFS helper function.

在java里,function modify list的话,caller里的list也会随着变化。因为pass list的时候实际上是pass in一个地址address。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容