劍指offer 面試34題


面試34題:

題目:二叉樹中和為某一值的路徑

題:輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。

解題代碼:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二維列表,內部每個列表表示找到的路徑
    def FindPath(self, root, expectNumber):
        # write code here
        if not root:
            return []
        result=[]
        
        def FindPathCore(root,path,currentNum):
            currentNum += root.val
            path.append(root)
            # 判斷是否達到葉子節點
            flag = (root.left==None and root.right==None)
            
            #如果到達葉子節點且當前值等於期望值
            if currentNum==expectNumber and flag:
                onepath=[]
                for node in path:
                    onepath.append(node.val)
                result.append(onepath)
                
            if currentNum<expectNumber:
                if root.left:
                    FindPathCore(root.left,path,currentNum)
                if root.right:
                    FindPathCore(root.right,path,currentNum)
            path.pop()
                
        FindPathCore(root,[],0)
        return result

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM