使用 Python 编写的修复错误二叉树的程序
假设,我们得到一个有问题的二叉树;其中一个节点的右子节点指针错误地指向二叉树中同一级别的另一个节点。因此,为了修复此问题,我们必须找出出现此错误的节点,并删除该节点及其后代,但错误指向的节点除外。我们返回固定二叉树的根节点。
因此,如果输入如下

我们可以看到 4 和 6 之间存在错误链接。4 的右子指针指向 6。
然后输出,即更正后的树的中序表示将为 − 2、3、5、6、7、8,
节点 4 被删除,因为它与节点 6 的链接错误。
为了解决这个问题,我们将遵循以下步骤 −
q := 一个包含根的新双端队列
p := 一个新的映射
visited := 一个新的集合
当 q 不为空时,执行
cur := 弹出 q 最左边的元素
如果 cur 存在于 accessed 中,则
is_left := p[p[cur, 0]]
grand_p := p[p[cur, 0]]
如果 is_left 不为 null,则
grand_p 的 left := null
否则,
grand_p 的右侧 := null
返回根节点
add(cur) of accessed
如果 cur 的左侧不为空,则
p[cur 的左侧] := 一个新的元组 (cur, 1)
将 cur 的左侧插入到 q 的末尾
如果 cur 的右侧不为空,则
p[cur 的右侧] := 一个新的元组 (cur, 0)
将 cur 的右侧插入到q
返回 root
让我们看看下面的实现以便更好地理解 −
示例
import collections class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def insert(temp,data): que = [] que.append(temp) while (len(que)): temp = que[0] que.pop(0) if (not temp.left): if data is not None: temp.left = TreeNode(data) else: temp.left = TreeNode(0) break else: que.append(temp.left) if (not temp.right): if data is not None: temp.right = TreeNode(data) else: temp.right = TreeNode(0) break else: que.append(temp.right) def make_tree(elements): Tree = TreeNode(elements[0]) for element in elements[1:]: insert(Tree, element) return Tree def search_node(root, element): if (root == None): return None if (root.data == element): return root res1 = search_node(root.left, element) if res1: return res1 res2 = search_node(root.right, element) return res2 def print_tree(root): if root is not None: print_tree(root.left) print(root.data, end = ', ') print_tree(root.right) def solve(root): q = collections.deque([root]) p, visited = dict(), set() while q: cur = q.popleft() if cur in visited: grand_p, is_left = p[p[cur][0]] if is_left: grand_p.left = None else: grand_p.right = None return root visited.add(cur) if cur.left: p[cur.left] = (cur, 1) q.append(cur.left) if cur.right: p[cur.right] = (cur, 0) q.append(cur.right) return root root = make_tree([5, 3, 7, 2, 4, 6, 8]) link_from = search_node(root, 4) link_to = search_node(root, 6) link_from.right = link_to print_tree(solve(root))
输入
root = make_tree([5, 3, 7, 2, 4, 6, 8]) link_from = search_node(root, 4) link_to = search_node(root, 6) link_from.right = link_to
输出
2, 3, 5, 6, 7, 8,
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

