Python 代码实现将表达式转化为二叉树
class Node: def init(self, value): self.value = value self.left = None self.right = None
def build_tree(expression): stack = [] for char in expression: if char.isalpha(): node = Node(char) stack.append(node) else: right_node = stack.pop() left_node = stack.pop() node = Node(char) node.left = left_node node.right = right_node stack.append(node) return stack.pop()
expression = '(A and (B or C)) or (D or (E and F))' root = build_tree(expression) print(root.value) print(root.left.value) print(root.left.left.value) print(root.left.right.value) print(root.right.value) print(root.right.left.value) print(root.right.right.value)
原文地址: http://www.cveoy.top/t/topic/nJaO 著作权归作者所有。请勿转载和采集!