【LeetCode 簡單題】67-二叉樹的所有路徑
阿新 • • 發佈:2018-11-07
宣告:
今天是第67道題。給定一個二叉樹,返回所有從根節點到葉子節點的路徑。以下所有程式碼經過樓主驗證都能在LeetCode上執行成功,程式碼也是借鑑別人的,在文末會附上參考的部落格連結,如果侵犯了博主的相關權益,請聯絡我刪除
(手動比心ღ( ´・ᴗ・` ))
正文
題目:給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
輸入: 1 / \ 2 3 \ 5 輸出: ["1->2->5", "1->3"] 解釋: 所有根節點到葉子節點的路徑為: 1->2->5, 1->3
解法1。
執行用時: 32 ms, 在Binary Tree Paths的Python提交中擊敗了82.28% 的使用者
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ if not root: return [] #題目要求為空時的返回結果 path = '' result = [] self.binaryTreePathsHelper(root,path,result) return result def binaryTreePathsHelper(self,root,path,result): if not root: return path += str(root.val) if root.left: binaryTreePathsHelper(root.left,path+'->',result) if root.right: binaryTreePathsHelper(root.right,path+'->',result) if root.left is None and root.right is None: result.append(path)
結尾
解法1:https://blog.csdn.net/yurenguowang/article/details/77678894