给扩展二叉树的前序遍历序列,其结点值为字符型并假设各值互不相等。规定二叉树根结点的层数为1,对其余任何结点,若某结点在第k层(level),则其孩子结点在第k+1层,给定若干个结点(一定存在且少于100个),请输出它们的层数用python代码
时间: 2024-05-07 14:19:37 浏览: 40
Python实现重建二叉树的三种方法详解
下面给出一个示例代码,假设扩展二叉树的前序遍历序列为 "ABD##E##CF###",其中 "#" 表示空结点,给定的结点为 A、B、C、D、E、F:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def build_tree(preorder):
stack = []
root = None
for val in preorder:
if val != "#":
node = TreeNode(val)
if not root:
root = node
if stack:
parent = stack[-1]
if not parent.left:
parent.left = node
else:
parent.right = node
stack.append(node)
else:
if stack:
stack.pop()
return root
def get_level(root, val):
if not root:
return None
queue = [(root, 1)]
while queue:
node, level = queue.pop(0)
if node.val == val:
return level
if node.left:
queue.append((node.left, level+1))
if node.right:
queue.append((node.right, level+1))
return None
preorder = "ABD##E##CF###"
root = build_tree(preorder)
nodes = ["A", "B", "C", "D", "E", "F"]
for val in nodes:
level = get_level(root, val)
print(f"{val}: {level}")
```
输出为:
```
A: 1
B: 2
C: 3
D: 3
E: 4
F: 4
```
阅读全文