力扣算法学习day11-3
226-翻转二叉树
题目
代码实现
class Solution {
public TreeNode invertTree(TreeNode root) {
LinkedList<TreeNode> queue = new LinkedList<>();
if(root == null){
return root;
}
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
while(len > 0){
TreeNode node = queue.poll();
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
len--;
}
}
return root;
}
}
101-对称二叉树
题目
代码实现
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left,root.right);
}
public boolean compare(TreeNode left,TreeNode right){
if(left == null && right != null){
return false;
} else if(left != null && right == null){
return false;
} else if(left == null && right == null){
return true;
} else if(left.val != right.val){
return false;
}
boolean wai = compare(left.left,right.right);
boolean nei = compare(left.right,right.left);
return nei && wai;
}
}
|