Python二叉树实现的思路及其代码示例,给出使用示例构造一棵二叉树并且画出这棵树
时间: 2024-03-01 13:47:05 浏览: 29
以下是Python实现二叉树的思路和代码示例:
1. 定义二叉树节点类:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
```
2. 构建二叉树:
```python
def build_tree(nodes):
if not nodes:
return None
root = TreeNode(nodes[0])
queue = [root]
i = 1
while queue and i < len(nodes):
node = queue.pop(0)
if nodes[i] is not None:
node.left = TreeNode(nodes[i])
queue.append(node.left)
i += 1
if i < len(nodes) and nodes[i] is not None:
node.right = TreeNode(nodes[i])
queue.append(node.right)
i += 1
return root
```
3. 画出二叉树:
```python
def print_tree(root):
if not root:
return
queue = [root]
res = []
while queue:
node = queue.pop(0)
if node:
res.append(str(node.val))
queue.append(node.left)
queue.append(node.right)
else:
res.append('null')
print(' -> '.join(res))
```
使用示例构造一棵二叉树并画出这棵树:
```python
nodes = [1, 2, 3, 4, 5, None, 6]
root = build_tree(nodes)
print_tree(root)
```
输出结果:
```
1 -> 2 -> 3 -> 4 -> 5 -> null -> 6 -> null -> null -> null -> null
```
相关推荐
![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_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)
![](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)