递归找路径m->n
作者:
崩溃青蛙
,
2024-08-17 15:15:24
,
所有人可见
,
阅读 1
#include<bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool postorder(TreeNode* root,TreeNode* n)//后序遍历查找路径m-n
{
if(!root)return false;
//遍历左右子树
if(root==n||postorder(root->left,n)||postorder(root->right,n))
{
//如果如果当前节点是目标节点n或在左右子树找到了目标节点
//输出结点的值
cout<<root->val<<' ';
return true;
}
}
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);
TreeNode* m=root;
TreeNode* n=root->right->left;
postorder(m,n);
return 0;
}