Same Tree
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.
判断两颗树是否相等。
思路:定义一个函数,判断两颗树是否都为空,如果都为空则返回true,其他情况都返回false,不断递归这两颗树的坐子树和右子树。根据返回的结果判断两颗树是否相等。
代码如下:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 10 11 12 13 14 bool isSameTree(struct TreeNode* p, struct TreeNode* q) { 15 if(p==NULL&&q==NULL) return true; 16 if(p==NULL||q==NULL) return false; 17 if(p->val!=q->val) return false; 18 19 return isSameTree(p->left, q->left)&&isSameTree(p->right, q->right); //递归调用函数 20 }