【6_100】Same Tree

Same Tree

Total Accepted: 97481 Total Submissions: 230752 Difficulty: Easy

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.

Subscribe to see which companies asked this question

这次卡在了递归的return使用上,原来可以一次return两个啊

错误写法:

else if(p != NULL && q != NULL && p->val == q->val) {
  isSameTree(p->left, q->left) ;

  isSameTree(p->right, q->right);
}

正确写法:

else if(p != NULL && q != NULL && p->val == q->val) {
  return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}

这次是C语言

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
if(p == NULL && q == NULL)
return true;
else if(p != NULL && q != NULL && p->val == q->val) {
return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
else
return false;
}
上一篇:python 内置函数 map filter reduce lambda


下一篇:cpu利用率和cpu 队列