【leetcode每日一题】100.same treet

阳光穿透心脏的1/2处 2022-08-05 08:42 125阅读 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.

解析:

判断两棵二叉树,是否是相等的。对于两棵树相同位置的节点来说,如果两个节点都为NULL,则这两个节点时相等的;如果一个节点为NULL,另一个节点不为NULL,则这两个节点不等;如果两个节点都不为NULL,则判断两个节点指向的值是否相等。

代码如下:

  1. /**
  2. * Definition for binary tree
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. bool isSameTree(TreeNode *p, TreeNode *q) {
  13. bool left,right;
  14. if(p==NULL&&q==NULL)
  15. return true;
  16. else if(p!=NULL&&q!=NULL)
  17. {
  18. if(p->val!=q->val)
  19. return false;
  20. left=isSameTree(p->left,q->left);
  21. right=isSameTree(p->right,q->right);
  22. return left&&right;
  23. }
  24. else
  25. return false;
  26. }
  27. };

发表评论

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

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

相关阅读

    相关 每日Leetcode 66.加

    题目描述: 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 你可以假设除了整数 0