码迷,mamicode.com
首页 > 其他好文 > 详细

输出二叉树中随机两个结点的最小公共父结点

时间:2015-04-14 02:02:27      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:二叉树

思路:当遇到一个结点是返回1,当左右子树都返回1的时候,即最小公共父节点。

//二叉树的数据结构
typedef struct MyStruct
{
    char data;
    struct MyStruct *leftChild;
    struct MyStruct *rightChild;
}Node, *Tree;
//查找方法
int findFirstFather(Tree root, char first, char second,char &destination){
    int i, j;
    if (root==NULL)
    {
        return 0;
    }
    if (root->data == first || root->data == second)
    {
        return 1;
    }
    else
    {
        i = findFirstFather(root->leftChild, first, second, destination);
        j = findFirstFather(root->rightChild, first, second, destination);
        if (i == 1 && j == 1)
        {
            destination = root->data;
        }
        if (i||j)
        {
            return 1;
        }
    }
    return 0;
}
输入:ABC##DE#G##F###
输出:D

输出二叉树中随机两个结点的最小公共父结点

标签:二叉树

原文地址:http://blog.csdn.net/u011426341/article/details/45035671

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!