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

careercup-树与图 4.8

时间:2014-12-06 15:23:24      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

4.8 你有两棵非常大的二叉树:T1,有几百万个结点;T2,有几百个结点。设计一个算法,判断T2是否为T1的子树。

如果T1有这么一个结点n,其子树与T2一模一样,则T2是T1的子树。也就是说,从结点n处把树砍掉,得到的树与T2完全相同。

 

C++实现代码:

#include<iostream>
#include<new>
#include<cmath>
using namespace std;

//Definition for binary tree
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

void createTree(TreeNode *&root)
{
    int i;
    cin>>i;
    if(i!=0)
    {
        TreeNode *tmp=new TreeNode(i);
        root=tmp;
        createTree(root->left);
        createTree(root->right);
    }
}

bool isSubTree(TreeNode *root1,TreeNode *root2)
{
    //root2为空时是任何数的子树
    if(root2==NULL)
        return true;
    //如果root2不为空,但是root1为空,则返回false
    if(root1==NULL)
        return false;
    if(root1->val==root2->val)
        return isSubTree(root1->left,root2->left)&&isSubTree(root1->right,root2->right);
    else
        return isSubTree(root1->left,root2)||isSubTree(root1->right,root2);
    return false;
}

int main()
{
    TreeNode *root1=NULL;
    TreeNode *root2=NULL;
    createTree(root1);
    createTree(root2);
    cout<<isSubTree(root1,root2)<<endl;
}

 

careercup-树与图 4.8

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/wuchanming/p/4148214.html

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