码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-07-05 21:13:19      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:资料   传递   nod   java   treenode   question   res   html   日期   

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

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

标签:资料   传递   nod   java   treenode   question   res   html   日期   

原文地址:http://www.cnblogs.com/jimmycheng/p/7123123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!