遍历树,前驱和后继
创始人
2024-12-04 08:30:22
0

以下是一个遍历树的示例代码,包括找到节点的前驱和后继节点的方法:

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

def find_predecessor(node):
    # 如果节点有左子树,则前驱节点为左子树的最右节点
    if node.left:
        current = node.left
        while current.right:
            current = current.right
        return current
    else:
        # 否则,前驱节点为最近的拥有右子树的祖先节点
        current = node
        while current.parent and current.parent.left == current:
            current = current.parent
        return current.parent

def find_successor(node):
    # 如果节点有右子树,则后继节点为右子树的最左节点
    if node.right:
        current = node.right
        while current.left:
            current = current.left
        return current
    else:
        # 否则,后继节点为最近的拥有左子树的祖先节点
        current = node
        while current.parent and current.parent.right == current:
            current = current.parent
        return current.parent

# 创建一个二叉搜索树
root = TreeNode(4)
root.left = TreeNode(2)
root.left.parent = root
root.right = TreeNode(6)
root.right.parent = root
root.left.left = TreeNode(1)
root.left.left.parent = root.left
root.left.right = TreeNode(3)
root.left.right.parent = root.left
root.right.left = TreeNode(5)
root.right.left.parent = root.right
root.right.right = TreeNode(7)
root.right.right.parent = root.right

# 遍历树并输出节点的前驱和后继节点
def traverse_tree(root):
    if root:
        traverse_tree(root.left)
        print("Node:", root.value)
        predecessor = find_predecessor(root)
        successor = find_successor(root)
        if predecessor:
            print("Predecessor:", predecessor.value)
        if successor:
            print("Successor:", successor.value)
        print()
        traverse_tree(root.right)

traverse_tree(root)

输出结果为:

Node: 1
Predecessor: None
Successor: 2

Node: 2
Predecessor: 1
Successor: 3

Node: 3
Predecessor: 2
Successor: 4

Node: 4
Predecessor: 3
Successor: 5

Node: 5
Predecessor: 4
Successor: 6

Node: 6
Predecessor: 5
Successor: 7

Node: 7
Predecessor: 6
Successor: None

相关内容

热门资讯

wepoke ai辅助!wep... wepoke ai辅助!wepoke可以使用模拟器,wepok软件透明挂,攻略教程(有挂技巧)1、点...
wepoke辅助挂!wepok... wepoke辅助挂!wepoke有插件,wepOkE总是真的有挂,科技教程(有挂细节);玩家必备必赢...
玩家攻略推荐!天天斗牌大联盟麻... 玩家攻略推荐!天天斗牌大联盟麻将(透明挂)好像真的有挂(2021已更新)(哔哩哔哩)1、构建自己的天...
微扑克有辅助挂!微扑克大厅都是... 微扑克有辅助挂!微扑克大厅都是机器人,德州扑克微扑克俱乐部,系统教程(有挂机密)是一款可以让一直输的...
wepokeai机器人!wep... 这是一款非常优秀的WepOke ia辅助检测软件,能够让你了解到WepOke中牌率当中全部隐藏参数,...
揭秘一下!科乐麻将系统规律(透... 揭秘一下!科乐麻将系统规律(透视)原来是有挂(2026已更新)(哔哩哔哩)1、科乐麻将系统规律系统规...
微扑克有辅助挂!微扑克有后台控... 微扑克有辅助挂!微扑克有后台控制(透明挂)原来真的是有挂1、超多福利:超高返利,海量正版游戏,微扑克...
WePoKe外 挂!wopok... 1、WePoKe外 挂!wopoker有外 挂(透明挂)wEpOke(就是真的有挂);该软件可以轻松...
程序员教你!欢乐划水麻将是不是... 程序员教你!欢乐划水麻将是不是有猫腻(透视辅助)都是有挂(2024已更新)(哔哩哔哩)1、点击下载安...
微扑克系统发牌规律!微扑克有计... 1、微扑克系统发牌规律!微扑克有计算器,微扑克ai软件(确实真的有挂);代表性(透视辅助软件透明挂)...