1. 程式人生 > >【二叉樹】判斷兩棵樹是否相同

【二叉樹】判斷兩棵樹是否相同

題目連結:https://leetcode.com/problems/same-tree/#/description

/**
 * 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 && q==NULL){
            return true;
        }else if((p==NULL&&q!=NULL)||(p!=NULL&&q==NULL)||(q->val!=p->val)){
            return false;
        }else{
            bool tmp=isSameTree(p->left,q->left);
            bool tmp1=isSameTree(p->right,q->right);
            if(tmp&&tmp1) return true;
            else return false;
        }
    }
};