您的位置:首页 > 编程语言

Leetcode在线编程same-tree

2016-12-04 22:10 281 查看

Leetcode在线编程same-tree

题目链接

Leetcode在线编程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.

题意

判断题目给定的2个二叉树是否相等

解题思路

先判断是否2个可能不能同时为空或者同时为非空(异或大法)

接着若有一个为空,则肯定两个都是空了

最后就是递归判断左右子树是否都是相等

AC代码

class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(!p ^ !q)
return false;
if(!p)
return true;
if(p->val == q->val)
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
else
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 编程