Determine if two binary trees are equal

前端 未结 7 2014
臣服心动
臣服心动 2020-12-04 22:33

What would be the efficient algorithm to find if two given binary trees are equal - in structure and content?

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 23:08

    bool identical(node* root1,node* root2){
        if(root1 == NULL && root2 == NULL)
            return true;
        if(root1==NULL && root2!=NULL || root1!=NULL && root2 == NULL)
            return false;
        if(root1->data == root2->data){
            bool lIdetical = identical(root1->left,root2->left);
            if(!lIdentical)
                return false;
            bool rIdentical = identical(root1->right,root2->identical);
            return lIdentical && rIdentical;
        }
        else{
            printf("data1:%d vs data2:%d",root1->data,root2->data);
            return false;
        }
    }
    

    I do not know if this is the most effecient but I think this works.

提交回复
热议问题