代码实现
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return compare(root.left,root.right);
}
public boolean compare(TreeNode left,TreeNode right){
if(left == null && right == null) return true;
else if(left != null && right == null) return false;
else if(left == null && right != null) return false;
else if(left.val != right.val) return false;
boolean out = compare(left.left,right.right);
boolean in = compare(left.right,right.left);
return out && in;
}
}
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root.left);
queue.offer(root.right);
while(!queue.isEmpty()){
TreeNode left = queue.poll();
TreeNode right = queue.poll();
if(left == null && right == null) continue;
if(left == null || right == null || left.val != right.val) return false;
queue.offer(left.left);
queue.offer(right.right);
queue.offer(left.right);
queue.offer(right.left);
}
return true;
}
}
分析
true
代码
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
else if(p == null && q != null) return false;
else if(p != null && q == null) return false;
else if(p.val != q.val) return false;
else return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(p);
queue.offer(q);
while(!queue.isEmpty()){
p = queue.poll();
q = queue.poll();
if(p == null && q == null) continue;
if(p == null || q == null || p.val != q.val) return false;
queue.offer(p.left);
queue.offer(q.left);
queue.offer(p.right);
queue.offer(q.right);
}
return true;
}
}
代码
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if(root == null && subRoot == null) return true;
else if(root == null || subRoot == null) return false;
else return isSameTree(root,subRoot) || isSubtree(root.left,subRoot) || isSubtree(root.right,subRoot);
}
public boolean isSameTree(TreeNode p,TreeNode q){
if(p == null && q == null) return true;
else if(p == null || q == null) return false;
else if(p.val != q.val) return false;
else return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}
) return false;
else return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}