c++实现二叉树后序遍历搜索节点并输出路径
时间: 2023-06-20 14:07:28 浏览: 112
用C++实现二叉树的查找功能
4星 · 用户满意度95%
二叉树的后序遍历是先遍历左子树,再遍历右子树,最后遍历根节点。因此,在搜索节点时也需要先递归遍历左子树和右子树,最后才能判断当前节点是否为目标节点。
以下是一个示例代码:
```c++
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool postorderTraversal(TreeNode* root, int target, vector<int>& path) {
if (root == NULL) return false; // 当前节点为空,返回false
bool found = false;
if (root->left) found = postorderTraversal(root->left, target, path); // 递归遍历左子树
if (root->right) found = postorderTraversal(root->right, target, path) || found; // 递归遍历右子树
if (root->val == target) found = true; // 当前节点为目标节点,将found设置为true
if (found) path.push_back(root->val); // 如果找到目标节点,则将当前节点的值添加到路径中
return found;
}
int main() {
// 构造一棵二叉树
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(8);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->left = new TreeNode(7);
root->right->right = new TreeNode(9);
int target = 7;
vector<int> path;
bool found = postorderTraversal(root, target, path);
if (found) {
cout << "Path to node " << target << ": ";
for (int i = path.size() - 1; i >= 0; i--) {
cout << path[i] << " ";
}
cout << endl;
} else {
cout << "Node " << target << " not found." << endl;
}
return 0;
}
```
在以上代码中,`postorderTraversal`函数返回一个bool值,表示是否找到目标节点。如果找到,则将路径上的节点值添加到`path`向量中。最后,根据`path`向量输出路径。
阅读全文