您的位置:首页 > 其它

(leetcode) Same Tree

2014-09-18 15:47 309 查看
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.

解题思路: 递归判断二叉树 根结点val是否相同,然后判断结构是否一样,调用递归。
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    bool function(TreeNode *p, TreeNode *q){
        if(p==NULL&&q==NULL)
            return true;
        if(p==NULL&&q!=NULL||p!=NULL&q==NULL||p->left!=NULL&&q->left==NULL||p->left==NULL&&q->left!=NULL||p->right==NULL&&q->right!=NULL||p->right!=NULL&&q->right==NULL)
            return false;
        return (p->val==q->val)&&(function(p->left,q->left))&&(function(p->right,q->right));
    }
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
        return function(p,q);
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: