```cpp
#include <iostream>
#include <vector>
using namespace std;
class TreeNode
{
public:
TreeNode *lchild;
TreeNode *rchild;
char value;
TreeNode(char c) : value(c)
{
lchild = NULL;
rchild = NULL;
}
};
TreeNode *findlowestCommonAncestor(TreeNode *root, TreeNode *input1, TreeNode *input2)
{
if (root == NULL || root == input1 || root == input2)
return root;
TreeNode *left = findlowestCommonAncestor(root->lchild, input1, input2);
TreeNode *right = findlowestCommonAncestor(root->rchild, input1, input2);
if (left != NULL && right != NULL)
return root;
return left == NULL ? right : left;
}
void findPath(TreeNode *root, TreeNode *input, vector<TreeNode *> &path, bool &isFind)
{
if (root == NULL || isFind == true)
{
return;
}
findPath(root->lchild, input, path, isFind);
findPath(root->rchild, input, path, isFind);
if (root == input || isFind == true)
{
path.emplace_back(root);
isFind = true;
}
}
int printPath(TreeNode *root, TreeNode *input1, TreeNode *input2)
{
vector<TreeNode *> path1;
vector<TreeNode *> path2;
bool flag = false;
findPath(root, input1, path1, flag);
flag = false;
findPath(root, input2, path2, flag);
for (int i = 0; i < path1.size() - 1; i++)
{
cout << path1[i]->value << "->";
}
for (int i = path2.size() - 1; i >= 0; i--)
{
cout << path2[i]->value << "->";
}
cout << "all disance is " << endl;
return path1.size() + path2.size() - 2;
}
int distance(TreeNode *root, TreeNode *input1, TreeNode *input2)
{
TreeNode *CommonAncestor = findlowestCommonAncestor(root, input1, input2);
return printPath(CommonAncestor, input1, input2);
}
int main()
{
TreeNode *A = new TreeNode('A');
TreeNode *root = A;
TreeNode *G = A->lchild = new TreeNode('G');
TreeNode *B = A->rchild = new TreeNode('B');
TreeNode *C = B->rchild = new TreeNode('C');
TreeNode *D = C->rchild = new TreeNode('D');
TreeNode *E = D->rchild = new TreeNode('E');
TreeNode *O = E->lchild = new TreeNode('O');
TreeNode *F = O->lchild = new TreeNode('F');
TreeNode *H = O->rchild = new TreeNode('H');
cout << distance(root, G, H) << endl;
cout << distance(root, A, F) << endl;
return 0;
}