以二叉链表作为二叉树的存储结构,创建二叉树,并编写用层次顺序遍历二叉树的方法,统计树中度为1 的结点个数。
时间: 2023-06-14 08:07:11 浏览: 114
二叉链表存储结构中,每个结点包含三个域,分别是数据域、左子树指针域和右子树指针域。下面是用二叉链表创建二叉树的代码:
```python
class TreeNode:
def __init__(self, val=None):
self.val = val
self.left = None
self.right = None
def create_binary_tree(node_list):
"""使用二叉链表创建二叉树"""
if not node_list:
return None
root = TreeNode(node_list[0])
nodes = [root]
j = 1
for node in nodes:
if node is not None:
node.left = TreeNode(node_list[j]) if node_list[j] is not None else None
nodes.append(node.left)
j += 1
if j == len(node_list):
return root
node.right = TreeNode(node_list[j]) if node_list[j] is not None else None
nodes.append(node.right)
j += 1
if j == len(node_list):
return root
else:
nodes.append(None)
nodes.append(None)
return root
```
使用层次遍历的方法遍历二叉树,可以按照从上到下、从左到右的顺序依次遍历每个结点。下面是用层次遍历二叉树的代码:
```python
from queue import Queue
def level_order_traversal(root):
"""层次遍历二叉树"""
if not root:
return []
res = []
queue = Queue()
queue.put(root)
while not queue.empty():
node = queue.get()
res.append(node.val)
if node.left:
queue.put(node.left)
if node.right:
queue.put(node.right)
return res
```
统计树中度为1的结点个数,可以在遍历二叉树的过程中,记录每个结点的度数,然后统计度数为1的结点个数。下面是统计度数为1的结点个数的代码:
```python
def count_degree_one_nodes(root):
"""统计树中度为1的结点个数"""
if not root:
return 0
queue = Queue()
queue.put(root)
count = 0
while not queue.empty():
node = queue.get()
degree = 0
if node.left:
degree += 1
queue.put(node.left)
if node.right:
degree += 1
queue.put(node.right)
if degree == 1:
count += 1
return count
```
完整代码如下:
```python
from queue import Queue
class TreeNode:
def __init__(self, val=None):
self.val = val
self.left = None
self.right = None
def create_binary_tree(node_list):
"""使用二叉链表创建二叉树"""
if not node_list:
return None
root = TreeNode(node_list[0])
nodes = [root]
j = 1
for node in nodes:
if node is not None:
node.left = TreeNode(node_list[j]) if node_list[j] is not None else None
nodes.append(node.left)
j += 1
if j == len(node_list):
return root
node.right = TreeNode(node_list[j]) if node_list[j] is not None else None
nodes.append(node.right)
j += 1
if j == len(node_list):
return root
else:
nodes.append(None)
nodes.append(None)
return root
def level_order_traversal(root):
"""层次遍历二叉树"""
if not root:
return []
res = []
queue = Queue()
queue.put(root)
while not queue.empty():
node = queue.get()
res.append(node.val)
if node.left:
queue.put(node.left)
if node.right:
queue.put(node.right)
return res
def count_degree_one_nodes(root):
"""统计树中度为1的结点个数"""
if not root:
return 0
queue = Queue()
queue.put(root)
count = 0
while not queue.empty():
node = queue.get()
degree = 0
if node.left:
degree += 1
queue.put(node.left)
if node.right:
degree += 1
queue.put(node.right)
if degree == 1:
count += 1
return count
if __name__ == '__main__':
node_list = [1, 2, 3, 4, None, 6, 7, None, None, None, None, None, None, 14]
root = create_binary_tree(node_list)
print(level_order_traversal(root)) # [1, 2, 3, 4, 6, 7, 14]
print(count_degree_one_nodes(root)) # 2
```
阅读全文