python绘制二叉树_二叉树的输入方法

python绘制二叉树_二叉树的输入方法在 Python 中 创建二叉树可以通过多种方式输入节点值 以下是几种常见的方法 递归创建 pythonclass 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

在Python中,创建二叉树可以通过多种方式输入节点值,以下是几种常见的方法:

递归创建

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)

使用栈解析前序遍历字符串

python

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

使用队列解析前序遍历字符串

python

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

以上代码展示了如何通过递归、栈和队列解析前序遍历字符串来创建二叉树。您可以根据需要选择合适的方法。

编程小号
上一篇 2026-05-07 19:20
下一篇 2026-05-07 19:16

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/45302.html