设计一个求结点x在二叉树中的双亲结点算法,c++实现
时间: 2024-06-13 20:07:51 浏览: 154
基于c++的数据结构的二叉树的遍历
以下是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;
}
```
阅读全文