python二叉树如何查找一个节点的父节点的代码
时间: 2024-05-12 20:17:47 浏览: 89
查找二叉树子结点的父结点的递规算法
5星 · 资源好评率100%
你好呀!很高兴为您服务~
Regarding your question, here's the Python code to find the parent node of a node in a binary tree:
```
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None # assume parent node is also stored in tree node
def find_parent(root, node):
if root is None:
return None
if root.left == node or root.right == node:
return root
left_result = find_parent(root.left, node)
if left_result:
return left_result
right_result = find_parent(root.right, node)
if right_result:
return right_result
# example usage:
root = TreeNode(1)
root.left = TreeNode(2)
root.left.parent = root
root.right = TreeNode(3)
root.right.parent = root
node = root.right
print(find_parent(root, node).val) # output: 1
```
Hope this helps! Let me know if you have any other questions.
阅读全文