使用 Python 删除二叉树中仅有一个子节点的所有节点的程序?
假设我们有一棵二叉树 root,我们必须删除仅有一个子节点的所有节点。
因此,如果输入类似于
则输出将为
为解决这个问题,我们将遵循以下步骤
定义一个名为 solve() 的方法,它将获取树根
如果根为 null,则
返回根
如果根的左节点为 null 且根的右节点为 null,则
返回根
如果根的左节点为 null,则
返回 solve(根的右节点)
如果根的右节点为 null,则
返回 solve(根的左节点)
根的左节点 := solve(根的左节点)
根的右节点 := solve(根的右节点)
返回根
范例
class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def print_tree(root): if root is not None: print_tree(root.left) print(root.data, end = ', ') print_tree(root.right) class Solution: def solve(self, root): if not root: return root if not root.left and not root.right: return root if not root.left: return self.solve(root.right) if not root.right: return self.solve(root.left) root.left = self.solve(root.left) root.right = self.solve(root.right) return root ob = Solution() root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.right.right = TreeNode(5) root.left.left.right = TreeNode(6) root.right.right.left = TreeNode(7) root.right.right.right = TreeNode(8) res = ob.solve(root) print_tree(res)
输入
root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.right.right = TreeNode(5) root.left.left.right = TreeNode(6) root.right.right.left = TreeNode(7) root.right.right.right = TreeNode(8)
输出
6, 1, 7, 5, 8,
广告