Python程式在樹的兩個節點間尋找最長路徑


假設我們有一棵二叉樹;我們必須找到樹中任意兩個節點之間最長的路徑。

所以,如果輸入像

 那麼輸出將是5 

為了解決這個問題,我們將遵循以下步驟

  • ans := 0

  • 定義函式getMaxPath()。它將佔用節點

  • 如果節點為null,則

    • 返回0

  • leftCnt := getMaxPath(節點的左節點)

  • rightCnt := getMaxPath(節點的右節點)

  • temp := 1 + leftCnt和rightCnt的最大值

  • ans := ans和l+r+1的最大值

  • 在main方法中執行以下操作 −

  • getMaxPath(root)

  • 返回ans

讓我們看看以下實現,以獲得更好的理解 −

示例

 線上演示

class TreeNode:
   def __init__(self, val, left=None, right=None):
      self.val = val
      self.left = left
      self.right = right

class Solution:
   def solve(self, root):
      self.ans = 0
      def getMaxPath(root):
         if root is None:
            return 0
         l = getMaxPath(root.left)
         r = getMaxPath(root.right)
         temp = max(l, r) + 1
         self.ans = max(self.ans, l + r + 1)
         return temp
      getMaxPath(root)
      return self.ans
ob = Solution()
root = TreeNode(2)
root.left = TreeNode(10)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(6)
print(ob.solve(root))

輸入

root = TreeNode(2)
root.left = TreeNode(10)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(6)

輸出

5

更新時間:10-10-2020

851次瀏覽

開啟你的 職業生涯

完成課程即可獲得證書

開始
廣告