二叉树的类的定义,构建方法
时间: 2024-03-01 19:06:30 浏览: 16
二叉树是一种非常常用的数据结构,它由节点(Node)和边(Edge)构成。每个节点包含一个数据元素和两个指向左右子节点的指针。下面是二叉树类的定义和构建方法:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BinaryTree:
def __init__(self, root=None):
self.root = root
def buildTree(self, nodes):
"""
构建一棵二叉树
:param nodes: List,节点列表,每个元素表示一个节点的值,None表示该节点为空
:return: TreeNode,二叉树的根节点
"""
if not nodes:
return None
n = len(nodes)
root = TreeNode(nodes[0])
queue = [root]
front = 0
index = 1
while index < n:
node = queue[front]
front += 1
if index < n and nodes[index] is not None:
node.left = TreeNode(nodes[index])
queue.append(node.left)
index += 1
if index < n and nodes[index] is not None:
node.right = TreeNode(nodes[index])
queue.append(node.right)
index += 1
return root
```
使用示例:
```python
# 构建一棵二叉树
nodes = [3,9,20,None,None,15,7]
bt = BinaryTree()
root = bt.buildTree(nodes)
```
这个方法使用了 BFS(广度优先搜索)的思想,从根节点开始,每次从队列中取出一个节点,分别构建它的左右子节点,然后将它们加入队列中。直到队列为空,整个二叉树就构建完成了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)