相同二叉树和对称二叉树
1.Leetcode100:相同二叉树
<1>题目
<2>解题思路
<3>示例代码
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){
return false;
}
return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right);
}
}
2.Leetcode101:对称二叉树
<1>题目
<2>解题思路
本题将二叉树的左右子树看成两棵树,加上根节点,依然是镜像
<3>代码示例
class Solution {
public boolean isSymmetric(TreeNode root) {
return issymmetric(root, root);
}
public boolean issymmetric(TreeNode p,TreeNode q){
if(p==null&&q==null){
return true;
}else if(p==null||q==null){
return false;
}else {
return q.val==p.val&&issymmetric(p.left,q.right)&&issymmetric(p.right,q.left);
}
}
}