算法题:python括号法反序列构造二叉树

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

def create_tree(chars):
    root, last_node = None, None
    is_left = False
    stack = []
    idx = 0

    while idx < len(chars):
        char = chars[idx]
        if char == '(':                            # 当为左括号时,下一个字符即为左节点
            is_left = True                         # 将标识符改为True
            stack.append(last_node)                # 将上一个节点加入栈中
        elif char == ',':                          # 当为逗号时,下一个节点为右节点  
            is_left = False                        # 将标识符改为False
        elif char == ')':                          # 当为右括号时,则一个子树结束
            is_left = False                        # 将标识符改为False
            stack.pop()                            # 将已完成构建的根节点出栈(需要理解)
        else:
            last_node = TreeNode(char)             # 构造节点
            if not root:
                root = last_node                   # 若无root则将last_node为根节点
            else:
                parent_node = stack[-1]            # 父节点为之前入栈的最后一个节点
                if is_left:                        # 根据标识符构建左右子树
                    parent_node.left = last_node   
                else:
                    parent_node.right = last_node
        idx += 1                                   # 遍历
    return root

def print_binary_tree(root, level=0, prefix="Root: "):
    if root:
        print('  ' * level + prefix + str(root.val))
        if root.left or root.right:
            print_binary_tree(root.left, level + 1, "Left: ")
            print_binary_tree(root.right, level + 1, "Right: ")

data = "A(B,C(D,E))"
root = create_tree(data)
print_binary_tree(root)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值