用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 BinaryTree {
private:
TreeNode* root;
public:
BinaryTree() : root(NULL) {}
// 插入节点
void insert(int val) {
TreeNode* node = new TreeNode(val);
if (root == NULL) {
root = node;
return;
}
TreeNode* curr = root;
while (curr != NULL) {
if (val < curr->val) {
if (curr->left == NULL) {
curr->left = node;
return;
}
curr = curr->left;
} else {
if (curr->right == NULL) {
curr->right = node;
return;
}
curr = curr->right;
}
}
}
// 查找节点
TreeNode* find(int val) {
TreeNode* curr = root;
while (curr != NULL) {
if (val == curr->val) {
return curr;
} else if (val < curr->val) {
curr = curr->left;
} else {
curr = curr->right;
}
}
return NULL;
}
// 获取指定节点的根节点路径
void getPath(int val) {
TreeNode* node = find(val);
if (node == NULL) {
cout << "Node not found!" << endl;
return;
}
getPathHelper(root, node);
}
private:
// 获取指定节点的根节点路径的辅助函数
bool getPathHelper(TreeNode* curr, TreeNode* node) {
if (curr == NULL) {
return false;
}
if (curr == node || getPathHelper(curr->left, node) || getPathHelper(curr->right, node)) {
cout << curr->val << " ";
return true;
}
return false;
}
};
int main() {
BinaryTree tree;
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(2);
tree.insert(4);
tree.insert(6);
tree.insert(8);
cout << "Path to node 2: ";
tree.getPath(2);
cout << endl;
cout << "Path to node 7: ";
tree.getPath(7);
cout << endl;
cout << "Path to node 9: ";
tree.getPath(9);
cout << endl;
return 0;
}
输出结果为:
Path to node 2: 5 3 2
Path to node 7: 5 7
Node not found!
Path to node 9:
``
原文地址: https://www.cveoy.top/t/topic/dI3j 著作权归作者所有。请勿转载和采集!