顺序表创建二叉树
时间: 2023-09-04 22:11:24 浏览: 37
顺序表创建二叉树的方法如下:
假设给定的顺序表为 `list`,二叉树的根节点为 `root`,索引从 0 开始。
1. 如果 `list` 为空,则二叉树为空,返回 `None`。
2. 否则,取出顺序表中的第一个元素,作为根节点 `root`。
3. 如果顺序表中的第二个元素不为空,则将其作为 `root` 的左子树,递归调用创建左子树的函数。
4. 如果顺序表中的第三个元素不为空,则将其作为 `root` 的右子树,递归调用创建右子树的函数。
5. 返回 `root`。
以下是示例代码实现:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def create_tree_from_list(lst, index):
if not lst:
return None
root_val = lst[0]
if root_val is None:
return None
root = TreeNode(root_val)
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < len(lst):
root.left = create_tree_from_list(lst[left_index:], left_index)
if right_index < len(lst):
root.right = create_tree_from_list(lst[right_index:], right_index)
return root
# 示例用法
lst = [1, 2, 3, None, None, 4, 5]
root = create_tree_from_list(lst, 0)
```