虽然做出来了,但是感觉写得不够简洁
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(!p&&!q) return true;
if(!p||!q) return false;
if(p->val==q->val)
{
if(!p->left&&!q->left&&!p->right&&!q->right)
return true;
if(p->left&&q->left||p->right&&q->right)
{
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
else
{
return false;
}
}
return false;
}
};
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null) return true;
if(p==null||q==null) return false;
if(p.val==q.val)
{
if(p.left==null&&q.left==null&&p.right==null&&q.right==null)
return true;
if(p.left!=null&&q.left!=null||p.right!=null&&q.right!=null)
{
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
else
{
return false;
}
}
return false;
}
}
Javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if(p===null&&q===null) return true;
if(p===null||q===null) return false;
if(p.val===q.val)
{
if(!p.left&&!q.left&&!p.right&&!q.right)
return true;
if(p.left&&q.left||p.right&&q.right)
{
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
else
{
return false;
}
}
return false;
};
最优解
C++,和我思路一样,但是写的很简洁,要学习
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if (p == NULL || q == NULL) return (p == q);
return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
};
Java,思路同上
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null) return false;
if(p.val == q.val)
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
return false;
}
代码实际做了两件事,判断节点是否存在,判断节点值是否相同