设计一个求结点x在二叉树中的双亲结点算法,c++实现
时间: 2024-06-13 14:07:51 浏览: 168
以下是C++实现的求结点x在二叉树中的双亲结点算法:
```c++
//定义二叉树结点
struct TreeNode {
char value;
TreeNode* LeftChild; TreeNode* RightChild;
TreeNode* parent;
};
//递归查找结点x的双亲结点
TreeNode* findParent(TreeNode* root, TreeNode* x) {
if (root == NULL || root == x) {
return NULL;
}
if (root->LeftChild == x || root->RightChild == x) {
return root;
}
TreeNode* left = findParent(root->LeftChild, x);
if (left != NULL) {
return left;
}
return findParent(root->RightChild, x);
}
//非递归查找结点x的双亲结点
TreeNode* findParent(TreeNode* root, TreeNode* x) {
if (root == NULL || root == x) {
return NULL;
}
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
if (node->LeftChild == x || node->RightChild == x) {
return node;
}
if (node->RightChild != NULL) {
s.push(node->RightChild);
}
if (node->LeftChild != NULL) {
s.push(node->LeftChild);
}
}
return NULL;
}
```
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20250102104920.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![h](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)