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