LeetCode判断两个二叉树的值与结果是否相同(isSameTree)

题目描述
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

二叉树结构的定义:

struct TreeNode
{
	int val ;
	TreeNode *left ;
	TreeNode *right ;
	TreeNode(int x) : val(x) , left(NULL) , right(NULL){}
}

本题可以采用递归与非递归算法实现

1、递归实现

bool isSameTree(TreeNode *p , TreeNode *q)
{
	if(p == NULL && q == NULL)
	{
		return true ;
	}
	else if(p == NULL || q == NULL)
	{
		return false ;
	}
	else if(p->val == q->val)
	{
		return isSameTree(p->left , q->left) && isSameTree(p->right , q->right) ;
	}
	else
	{
		return false ;
	}
}

2、非递归实现

bool isSameTree(TreeNode *p , TreeNode *q)
{
	if(p == NULL && q == NULL)
    {
        return true ;
    }
    else if(p == NULL || q == NULL)
    {
        return false ;
    }
    else
    {
        queue<TreeNode*> pq , qq ;
        vector<int> pv , qv ;
        pq.push(p) ;
        qq.push(q) ;
        pv.push_back(p->val) ;
        qv.push_back(q->val) ;
        while(!pq.empty() || !qq.empty())
        {
            if(pv.size() != qv.size() || pq.size() != qq.size())
            {
                return false ;
            }
            for(int i = 0 ; i < pv.size() ; i++)
            {
                if(pv[i] != qv[i])
                {
                    return false ;
                }
            }

            pv.clear() ;
            qv.clear() ;

            int start , xend ;
            start = 0 ;
            xend = pq.size() ;
            while(start++ < xend)
            {
                TreeNode * tempp = pq.front() ;
                TreeNode * tempq = qq.front() ;
                pq.pop() ;
                qq.pop() ;
                if(tempp->left != NULL)
                {
                    pq.push(tempp->left) ;
                    pv.push_back(tempp->left->val) ;
                }
                else
                {
                    pv.push_back(INT_MAX) ;
                }
                if(tempq->left != NULL)
                {
                    qq.push(tempq->left) ;
                    qv.push_back(tempq->left->val) ;
                }
                else
                {
                    qv.push_back(INT_MAX) ;
                }
                if(tempp->right != NULL)
                {
                    pq.push(tempp->right) ;
                    pv.push_back(tempp->right->val) ;
                }
                else
                {
                    pv.push_back(INT_MAX) ;
                }
                if(tempq->right != NULL)
                {
                    qq.push(tempq->right) ;
                    qv.push_back(tempq->right->val) ;
                }
                else
                {
                    qv.push_back(INT_MAX) ;
                }
            }
        }
        return true ;
}
posted @ 2019-04-25 19:40  luo...ye  阅读(38)  评论(0)    收藏  举报