用 Python 编写的程序,用于从二叉树中删除所有具有偶数值的叶子
programmingpythonserver side programming
假设我们有一棵二叉树,我们将反复删除所有具有偶数值的叶子。删除所有内容后,如果只有具有偶数值的根,则也将被删除。
因此,如果输入如下
则输出将是
为了解决这个问题,我们将遵循以下步骤 −
定义一个函数solve()。这将获取根节点
如果根节点为空,则
返回空值
根节点的左侧:=solve(根节点的左侧)
根节点的右侧:=solve(根节点的右侧)
如果根节点是叶子节点,并且根节点的数据为偶数,则
返回空值
返回根节点
让我们看看下面的实现以便更好地理解 −
示例
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,