在Python中,创建二叉树可以通过多种方式输入节点值,以下是几种常见的方法:
递归创建
class Node:def __init__(self, k=None, l=None, r=None):self.key = kself.left = lself.right = rdef create(root):a = input('Enter a key: ')if a == '':return Noneelse:root = Node(k=a)root.left = create(root.left)root.right = create(root.right)return rootif __name__ == '__main__':root = Noneroot1 = create(root)
使用栈解析前序遍历字符串
class TreeNode:def __init__(self, rootObj=None, leftChild=None, rightChild=None):self.key = rootObjself.leftChild = leftChildself.rightChild = rightChilddef createTreeByInput(self, root):tmpKey = input('Please input a key, input for Null: ')if tmpKey == '':root = Noneelse:root = TreeNode(rootObj=tmpKey)root.leftChild = self.createTreeByInput(root.leftChild)root.rightChild = self.createTreeByInput(root.rightChild)return root
使用队列解析前序遍历字符串
from collections import dequedef array_to_bst(array):if not array:return Noneroot = TreeNode(array)queue = deque([root])i = 1while queue and i < len(array):node = queue.popleft()if array[i] is not None:node.left = TreeNode(array[i])queue.append(node.left)i += 1if i < len(array) and array[i] is not None:node.right = TreeNode(array[i])queue.append(node.right)i += 1return root

