用 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.