简介
以前觉得这个问题还是挺难的. 后来发现其实也很简单. 直接上代码.
code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x): val(x), left(nullptr), right(nullptr){}
};
int level = 0;
vector<TreeNode*> path1;
vector<TreeNode*> path2;
TreeNode* p;
bool dfs(TreeNode *n, vector<TreeNode*> &path, TreeNode *p){
if(n == p){
path.push_back(n);
return true;
}
if(n->left){
if(dfs(n->left, path, p)){
path.push_back(n);
return true;
}
}
if(n->right){
if(dfs(n->right, path, p)){
path.push_back(n);
return true;
}
}
return false;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
}
int main(){
TreeNode * a = new TreeNode(3);
TreeNode * b = new TreeNode(5);
TreeNode * c = new TreeNode(1);
TreeNode * d = new TreeNode(6);
TreeNode * e = new TreeNode(2);
TreeNode * f = new TreeNode(0);
TreeNode * g = new TreeNode(8);
TreeNode * h = new TreeNode(7);
TreeNode * i = new TreeNode(4);
a->left = b;
a->right = c;
b->left = d;
b->right = e;
e->left = h;
e->right = i;
c->left = f;
c->right = g;
TreeNode * z = h;
dfs(a, path1, z);
for(auto it : path1){
cout << it->val << std::endl;
}
}