OJ练习21——T100 Same Tree

遇到树了!终于看起来高大上一点了= =

比较两棵二叉树,相等则返回true。

【思路】

递归,if(p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right)) return true.

注意还要考虑特殊情况。

【my code】

/**
 * Definition for binary tree
 * 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)  return false;
        if(p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right))
            return true;
        return false;
    }
};

【评价】

耗时6ms,看结果不算是高效算法。先这样。

原文地址:https://www.cnblogs.com/ketchups-notes/p/4443338.html