【面試題34】二叉樹中和爲某一值的路徑

在這裏插入圖片描述
Python題解

#解法一,遞歸,容易調用棧溢出。
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二維列表,內部每個列表表示找到的路徑
    def __init__(self):
        self.paths = []
    
    def FindPath(self, root, expectNumber):
        if not root: return []
        def helper(root, exceptSum, path, currentSum):
            currentSum += root.val
            path.append(root.val)
            isLeaf = root.left == None and root.right == None
            if currentSum == exceptSum and isLeaf:
                self.paths.append(path)
            if root.left:
                helper(root.left, exceptSum, path[:], currentSum)
            if root.right:
                helper(root.right, exceptSum, path[:], currentSum)
        path = []
        currentSum = 0
        helper(root, expectNumber, path, currentSum)
        return self.paths
#解法二,前序遍歷
class Solution:
    # 返回二維列表,內部每個列表表示找到的路徑
    def __init__(self):
        self.paths = []
    
    def FindPath(self, root, expectNumber):
        if not root: return []
        def helper(root, exceptSum, path, currentSum):
            currentSum += root.val
            path.append(root.val)
            isLeaf = root.left == None and root.right == None
            if currentSum == exceptSum and isLeaf:
                self.paths.append(path[:])
            if root.left:
                helper(root.left, exceptSum, path[:], currentSum)
            if root.right:
                helper(root.right, exceptSum, path[:], currentSum)
            path.pop()
        path = []
        currentSum = 0
        helper(root, expectNumber, path, currentSum)
        return self.paths

考點

  • 考查分析複雜問題的思維能力。遇到這個問題的時候,如果一下子沒有思路,則不妨從一個具體的例子開始,一步步分析路徑上包含哪些節點,這樣就能找出其中的規律,從而想到解決方案;
  • 考查對二叉樹的前序遍歷的理解。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章