1. 程式人生 > >LeetCode 257. Binary Tree Paths (二叉樹路徑)

LeetCode 257. Binary Tree Paths (二叉樹路徑)

res owin arr nod def 所有 fun href binary

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 (二叉樹路徑)