package tree;
import java.util.Deque;
import java.util.LinkedList;
public class LeetCode226 {
public static void main(String[] args) {
System.out.print("待定");
}
//递归
public static void invertTree(TreeNode root) {
if(root==null) {
return;
}
swap(root);
invertTree(root.left);
invertTree(root.right);
}
public static void swap(TreeNode root) {
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
}
//迭代
public static void invertTree02(TreeNode root) {
Deque<TreeNode> de = new LinkedList<>();
if(root ==null) {
return;
}
de.addFirst(root);
while(!de.isEmpty()) {
TreeNode temp = de.peekFirst();
swap(temp);
de.pollFirst();
de.addFirst(temp.right);
de.addFirst(temp.left);
}
}
}
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left,root.right);
}
public static boolean compare(TreeNode left,TreeNode right) {
if(left==null&&right!=null)return false;
else if(right==null&&left!=null)return false;
else if(right==null&&left==null)return true;
else if(left.val!=right.val)return false;
boolean outsize = compare(left.left,right.right);
boolean insize = compare(left.right,right.left);
return outsize&&insize;
}
//迭代法
public boolean isSymmetric(TreeNode root) {
if(root==null) {
return true;
}
Deque<TreeNode> de = new LinkedList<>();
de.addLast(root.left);
de.addLast(root.right);
while(!de.isEmpty()) {
TreeNode left = de.peekFirst();
de.pollFirst();
TreeNode right = de.peekFirst();
de.pollFirst();
if(left==null&&right==null) {
continue;
}
if(left==null||right==null||(left.val!=right.val)) {
return false;
}
de.addLast(left.left);
de.addLast(right.right);
de.addLast(left.right);
de.addLast(right.left);
}
return true;
}
}
?