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. 对称二叉树:先跳过
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; } }
标签:right,temp,part02,que,二叉树,深度,null,root From: https://www.cnblogs.com/hewx/p/18394968