[leetcode]: 100. Same Tree

红太狼 2022-06-16 14:46 243阅读 0赞

1.题目

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.

判断两棵二叉树是否相等。相等的定义是:结构相同,节点的元素值相同

2.分析

可以用递归来实现。
对于每个根结点
1)节点元素值是否相同
2)左子树是否相同
3)右子树是否相同

3.代码

  1. bool isSameTree(TreeNode* p, TreeNode* q) {
  2. if (p == NULL && q == NULL)
  3. return true;
  4. else if ((p == NULL && q != NULL) || (p != NULL &&q == NULL))
  5. return false;
  6. return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
  7. }

发表评论

表情:
评论列表 (有 0 条评论,243人围观)

还没有评论,来说两句吧...

相关阅读

    相关 #100 Same Tree

    按照通过率,第三的需要买书(还是过段时间再说吧……),那么就来做第四题咯 [\100 Same Tree][100 Same Tree] 这道题同样很简单,一看就是需