100. Same Tree(Tree)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyuanzong/article/details/80174002

https://leetcode.com/problems/same-tree/description/

题目:判断2课二叉树是否相同

思路:任何一种遍历都可以,我采用的是先序遍历,然后直接比较相应位置的元素即可。

代码:

class Solution {
public:
    bool sameTree(TreeNode* p , TreeNode* q){

         if(!p&&!q) return 1;
         if((!p&&q)||(!q&&p)||(p->val!=q->val)) return 0;

         return sameTree(p->left,q->left)&&sameTree(p->right,q->right);

    }
    bool isSameTree(TreeNode* p, TreeNode* q) {
         return sameTree(p,q);
    }
};

猜你喜欢

转载自blog.csdn.net/tangyuanzong/article/details/80174002