您的位置:首页 > 职场人生

二叉树两个结点的最低公共父结点 【微软面试100题 第七十五题】

2014-11-23 13:40 465 查看
题目要求:

  输入二叉树中的两个结点,输出这两个及诶单在数中最低的共同父结点。

题目分析:





  还有一种情况:如果输入的两个结点中有一个或两个结点不在二叉树中,则输出没有共同父结点;

  因此,可以在程序中定义一个flag=0,找到一个点之后flag就加1,最后判断的时候,如果flag=2,则说明在二叉树中找到了输入的两个结点。

代码实现:

  
#include <iostream>
#include <stack>

using namespace std;

typedef struct BinaryTree
{
    struct BinaryTree *left,*right;
    int data;
}BinaryTree;

int flag = 0;
void initTree(BinaryTree **p,BinaryTree **a,BinaryTree **b);
BinaryTree *GetLowestParent(BinaryTree *root,BinaryTree *X,BinaryTree *Y);

int main(void)
{
    BinaryTree *root,*a,*b;
    initTree(&root,&a,&b);

    BinaryTree *parent = GetLowestParent(root,a,b);
    if(parent && flag==2)
        cout << "最低公共父结点的值为:" << parent->data << endl;
    else
        cout << "没有最低公共父结点!" << endl;

    a = new BinaryTree;
    flag = 0;
    parent = GetLowestParent(root,a,b);
    if(parent && flag==2)
        cout << "最低公共父结点的值为:" << parent->data << endl;
    else
        cout << "没有最低公共父结点!" << endl;

    return 0;
}
//      10
//     / \
//    5   12
//   / \
//  4   7
void initTree(BinaryTree **p,BinaryTree **a,BinaryTree **b)
{
    *p = new BinaryTree;
    (*p)->data = 10;
 
    BinaryTree *tmpNode = new BinaryTree;
    tmpNode->data = 5;
    (*p)->left = tmpNode;
 
    tmpNode = new BinaryTree;
    *b = tmpNode;
    tmpNode->data = 12;
    (*p)->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    BinaryTree *currentNode = (*p)->left;
 
    tmpNode = new BinaryTree;
    *a = tmpNode;
    tmpNode->data = 4;
    currentNode->left = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 7;
    currentNode->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
    
    cout << "二叉树为:" <<endl;
    cout << "     " << 10<<endl;
    cout << "    " <<"/" << "  "<< "\\" <<endl;
    cout << "   " << 5 << "    " << 12 << endl;
    cout << " " <<"/" << "  "<< "\\" <<endl;
    cout << 4 << "    " << 7 << endl;
}
BinaryTree *GetLowestParent(BinaryTree *root,BinaryTree *X,BinaryTree *Y)
{
    if(root == NULL)
        return NULL;
    if(X==root || Y==root)
    {
        flag++;
        return root;
    }
    BinaryTree *left = GetLowestParent(root->left,X,Y);
    BinaryTree *right = GetLowestParent(root->right,X,Y);
    if(left==NULL && right==NULL)
        return NULL;
    else if(left==NULL)
        return right;
    else if(right==NULL)
        return left;
    else
        return root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐