leetcode刷题14天
100. Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
代码:
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;
else
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
}
- Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
代码:
class Solution {
public boolean isSymmetric(TreeNode p,TreeNode q) {
if(p==null&&q==null)
return true;
if(p==null||q==null)
return false;
if(p.val == q.val)
return isSymmetric(p.left,q.right)&&isSymmetric(p.right,q.left);
else
return false;
}
public boolean isSymmetric(TreeNode root) {
return isSymmetric(root,root);
}
}