100. Same Tree

来源:互联网 发布:幼儿园虐童 知乎 编辑:程序博客网 时间:2024/06/02 02:23

题目:

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.

思路:

像这种需要遍历树的就采用递归算法,这个题中,结束条件还是比较多的,要考虑到到两个树都为空时,他们就是相同的;如果一个树为空,一个树不为空就可以得到这两个树是不同的树;若两个根的节点的值不相同,也可以得到这是不同的树,所以要注意不要漏掉结束条件。


代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p == NULL && p==NULL)
        {
            return true;
        }
        else if((p==NULL && q!=NULL)||(p!=NULL && q==NULL))
        {
            return false;   
        }
        else if(p!=NULL &&q!=NULL)
        {
            if(p->val != q->val)
            {
                return false;
            }
            else
            {
                bool l = isSameTree(p->left, q->left);
                bool r = isSameTree(p->right, p->right);
                if(l && r)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
};

0 0
原创粉丝点击