c++二叉树输入一个值求双亲
时间: 2023-08-06 17:07:02 浏览: 51
好的,我可以回答这个问题。首先,需要明确二叉树的双亲节点指的是该节点的父节点。如果想要获取一个节点的双亲节点,需要遍历整个二叉树,找到该节点的父节点。
下面是一个简单的C++二叉树代码,用于输入一个值并求双亲:
```c++
#include<iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* findParent(TreeNode* root, int x) {
if (root == NULL) {
return NULL;
}
if ((root->left != NULL && root->left->val == x) || (root->right != NULL && root->right->val == x)) {
return root;
}
TreeNode* left = findParent(root->left, x);
TreeNode* right = findParent(root->right, x);
if (left != NULL) {
return left;
}
if (right != NULL) {
return right;
}
return NULL;
}
};
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
Solution solution;
TreeNode* parent = solution.findParent(root, 6);
if (parent == NULL) {
cout << "该节点没有双亲节点" << endl;
}
else {
cout << "该节点的双亲节点为:" << parent->val << endl;
}
return 0;
}
```
上面的代码中,我们使用了递归遍历整个二叉树,找到目标节点的父节点。在递归过程中,如果找到目标节点的父节点,则直接返回该父节点即可。如果没有找到,返回NULL。