用 Python 刪除二叉樹中所有具有偶數值的葉子的程式


假設我們有二叉樹,我們會重複刪除所有具有偶數值的葉子。刪除完所有葉子後,如果只有根具有偶數值,根也會被刪除。

因此,如果輸入如下


則輸出將為


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

  • 定義一個函式 solve() 。這將採用根

  • 如果根為 null,則

    • 返回 null

  • 根的左節點 := solve(根的左節點)

  • 根的右節點 := solve(根的右節點)

  • 如果根是葉子並且根的資料為偶數,則

    • 返回 null

  • 返回根

我們來看看下面的實現,以便更好地理解

示例

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

def inorder(root):
   if root:
      inorder(root.left)
      print(root.data, end = ', ')
      inorder(root.right)

class Solution:
   def solve(self, root):
      if not root:
         return None

      root.left = self.solve(root.left)
      root.right = self.solve(root.right)

      if not root.left and not root.right and root.data % 2 == 0:
         return None
      return root

ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
ob.solve(root)
inorder(root)

輸入

root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)

輸出

13, 16, 7, 14,

更新於:2020 年 10 月 7 日

349 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.