二叉树 最小路径


```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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值