学习目标:
掌握递归法、层序遍历法、迭代(栈)法解决翻转二叉树和判断二叉树是否对称
1.翻转二叉树
思路:交换每个节点的左右孩子
1.递归法:只能用前序或者后序遍历二叉树,因为如果使用中序,中途会将左右孩子互换,会把某些节点的左右孩子翻转了两次。
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
invertTree(root.left);
invertTree(root.right);
swap(root);
return root;
}
public void swap(TreeNode root){
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}
2.bfs层序遍历法
层序遍历也是一样的思路,代码较简单
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
Queue<TreeNode> st = new LinkedList<>();
st.add(root);
while(!st.isEmpty()){
int size = st.size();
while(size-->0){
TreeNode temp = st.poll();
swap(temp);
if(temp.left!=null)st.add(temp.left);
if(temp.right!=null)st.add(temp.right);
}
}
return root;
}
public void swap(TreeNode root){
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}
2.判断对称二叉树
1.递归法:使用了后序遍历,为什么呢,因为要返回到根节点再比较,这样说比较难理解,如果看代码就好理解了,dfs找到了最底下的进行判断,然后返回答案上来,如果判断外侧和内测是否都为true的那串“中代码”放在前面或者中间都会影响答案。
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 true;
else if(left == null || right == null || left.val != right.val) return false;
else{
//比较外侧
boolean wai = compare(left.left,right.right);//左
//比较内测
boolean nei = compare(left.right,right.left);//右
return wai && nei;//中
}
}
}
2.双端队列
思路是一样的,弹出队列两边的数进行比较,然后再按比较的顺序放入队列
class Solution {
public boolean isSymmetric(TreeNode root) {
Deque<TreeNode> dq = new LinkedList<>();
dq.addFirst(root.left);
dq.addLast(root.right);
while (!dq.isEmpty()) {
TreeNode left = dq.pollFirst();
TreeNode right = dq.pollLast();
if (left == null && right == null) continue;
else if (left == null || right == null || left.val != right.val) return false;
else {
dq.addFirst(left.left);
dq.addLast(right.right);
dq.addFirst(left.right);
dq.addLast(right.left);
}
}
return true;
}
}