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

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


题目标签:Tree

  这道题目给了我们一个二叉树,让我们记录所有的路径,返回一个array string list。 我们可以另外设一个findPaths function, 代入参数是node 和 String path。在设一个List<String> res 在两个funciton之外。

  遍历所有的点,对于每一个点:

    1。如果这个点是leaf node, 到底了,那么添加path 进res。

    2。如果这个点还有left child,那么递归代入node.left 和 path + "->" + left的值。

    3。如果这个点还有right child, 那么递归代入node.right 和 path + "->" + right的值。

findPaths function也不需要return,因为如果到底了,直接加入这个path就可以了,它也不会继续递归代入了。

 

 

Java Solution:

Runtime beats 68.03% 

完成日期:07/05/2017

关键词:Tree

关键点:设一个function代入参数值是node 和 String path , 利用path 来传递每一次的点

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution 
11 {
12     List<String> res = new ArrayList<String>();
13     
14     public List<String> binaryTreePaths(TreeNode root) 
15     {
16         if(root == null)
17             return res;
18         
19         findPaths(root, String.valueOf(root.val));
20         
21         return res;
22     }
23     
24     public void findPaths(TreeNode node, String path)
25     {
26         if(node.left == null && node.right == null)
27             res.add(path);
28             
29         if(node.left != null)
30             findPaths(node.left, path + "->" + node.left.val);
31         
32         if(node.right != null)
33             findPaths(node.right, path + "->" + node.right.val);
34         
35         
36     }
37 }

参考资料:

https://segmentfault.com/a/1190000003465753

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

posted @ 2017-07-05 19:33  Jimmy_Cheng  阅读(197)  评论(0编辑  收藏  举报