leetcode 100. Same Tree

墨蓝 2022-07-26 11:19 200阅读 0赞

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.

  1. void traverse(struct TreeNode* p, struct TreeNode* q, bool *f)
  2. {
  3. if (!*f)
  4. return;
  5. if (p == NULL&&q != NULL || p != NULL&&q == NULL)
  6. {
  7. *f = false;
  8. return;
  9. }
  10. if (p != NULL&&q != NULL)
  11. {
  12. if (p->val != q->val)
  13. {
  14. *f = false;
  15. return;
  16. }
  17. traverse(p->left, q->left,f);
  18. traverse(p->right, q->right,f);
  19. }
  20. return;
  21. }
  22. bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
  23. bool f = true;
  24. traverse(p, q, &f);
  25. return f;
  26. }

accept

发表评论

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

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

相关阅读

    相关 #100 Same Tree

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