小蝌蚪找妈妈编程代码
时间: 2023-09-30 08:13:02 浏览: 29
以下是一个简单的 Python 代码示例:
```python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def build_tree(preorder, inorder):
if not preorder or not inorder:
return None
root_value = preorder.pop(0)
root = Node(root_value)
inorder_index = inorder.index(root_value)
root.left = build_tree(preorder, inorder[:inorder_index])
root.right = build_tree(preorder, inorder[inorder_index+1:])
return root
def find_path(root, target):
if not root:
return []
if root.value == target:
return [root.value]
left_path = find_path(root.left, target)
if left_path:
return [root.value] + left_path
right_path = find_path(root.right, target)
if right_path:
return [root.value] + right_path
return []
preorder = [1, 2, 4, 7, 3, 5, 6, 8]
inorder = [4, 7, 2, 1, 5, 3, 8, 6]
root = build_tree(preorder, inorder)
path = find_path(root, 5)
print(path)
```
该代码实现了根据先序遍历和中序遍历构建二叉树,并找到指定节点的路径。其中,先序遍历和中序遍历分别为 `preorder` 和 `inorder` 数组,构建的二叉树的根节点为 `root`,指定节点为 `target`。