python二叉树如何查找一个节点的父节点的代码
时间: 2024-05-12 18:17:47 浏览: 58
你好呀!很高兴为您服务~
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.
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)