Day14|第六章 二叉树 part02| 226.翻转二叉树| 101. 对称二叉树| 104.二叉树的最大深度|111.二叉树的最小深度
226.翻转二叉树(递归只能前序或者后序,中序不行)
class Solution { public TreeNode invertTree(TreeNode root) { if(root == null) return null; swap(root); 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; } }
01. 对称二叉树:
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;} if(left != null && right == null){return false;} if(left == null && right == null){return true;} if(left.val != right.val){return false;} boolean compareOutside = compare(left.left, right.right); boolean compareInside = compare(left.right, right.left); return compareOutside && compareInside; } }
104.二叉树的最大深度
class Solution { public int maxDepth(TreeNode root) { if(root == null) return 0; Queue<TreeNode> que = new LinkedList<>(); int depth = 0; que.offer(root); while(!que.isEmpty()){ int size = que.size(); for(int i = 0; i < size; i++){ TreeNode temp = que.poll(); if(temp.left != null){ que.offer(temp.left); } if(temp.right != null){ que.offer(temp.right); } } //while 循环一次+1 depth++; } return depth; } }
111.二叉树的最小深度: 如果一个节点左,右都是空就是最小深度
class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; Queue<TreeNode> que = new LinkedList<>(); int depth = 0; que.offer(root); while(!que.isEmpty()){ //如果左右都为空就返回。 int size = que.size(); depth++; for(int i = 0; i < size; i++){ TreeNode temp = que.poll(); if(temp.left == null && temp.right == null){ return depth; } if(temp.left != null){ que.offer(temp.left); } if(temp.right != null){ que.offer(temp.right); } } } return depth; } }