104. Maximum Depth of Binary Tree
- 思路
- 求Maxium Depth其实就是求根节点的高度
- Depth 是某一节点到跟节点的距离,遍历用前序, 中左右,因为是从上开始1,2,3
- Height 是某一节点到叶子节点的距离,遍历用后续,左右中 ,因为是从下开始1,2,3
-
java class Solution { public int maxDepth(TreeNode root) { if (root == null){ return 0; } int left = maxDepth(root.left); //左 int right = maxDepth(root.right); //右 return 1 + Math.max(left, right); //中 } }
- 迭代法(层序遍历BFS)
- 其实层序遍历本来就是一层一层下来,算size的时候depth+1就行了
-
java class Solution { public int maxDepth(TreeNode root) { int res = 0; if (root == null){ return 0; } Queue queue = new LinkedList<>(); queue.add(root); while(!queue.isEmpty()){ int size = queue.size(); res++; while(size > 0){ TreeNode temp = queue.poll(); if(temp.left != null){ queue.add(temp.left); } if(temp.right != null){ queue.add(temp.right); } size--; } } return res; } }
- 求Maxium Depth其实就是求根节点的高度
559. Maximum Depth of N-ary Tree
- 思路
- 跟[[104. Maximum Depth of Binary Tree]]思路类似
- 后序遍历递归
-
java class Solution { public int maxDepth(Node root) { if (root == null){ return 0; } int depth = 0; //卡哥题解里这里有个判断children != null 的剪枝我给去掉了,为了对齐104的做法,初学者变化不需要太多 for(Node child : root.children){ depth = Math.max(depth, maxDepth(child)); } return depth +1; } }
- BFS迭代
-
java class Solution { public int maxDepth(Node root) { if (root == null){ return 0; } int depth = 0; Queue que = new LinkedList<>(); que.add(root); while( !que.isEmpty()){ int size = que.size(); depth++; while(size > 0 ){ Node temp = que.poll(); for( Node child : temp.children){ if(child != null){ que.add(child); } } size--; } } return depth; } }
111. Minimum Depth of Binary Tree
- 思路
- 跟[[104. Maximum Depth of Binary Tree]]很像
- 由于不能算depth = 1这种情况,所以要加conditions
-
java class Solution { public int minDepth(TreeNode root) { if (root == null){ return 0; } int left = minDepth(root.left); int right = minDepth(root.right); if (root.left == null && root.right != null){ return 1 + right; } if (root.right == null && root.left != null){ return 1 + left; } return 1 + Math.min(left, right); } }
- 层序遍历
-
javascript class Solution { public int minDepth(TreeNode root) { int res = 0; if (root == null){ return 0; } Queue queue = new LinkedList<>(); queue.add(root); while(!queue.isEmpty()){ int size = queue.size(); res++; while( size > 0){ TreeNode temp = queue.poll(); //只要遍历到叶子节点就可以直接return if(temp.left == null && temp.right == null){ return res; } if (temp.left != null){ queue.add(temp.left); } if (temp.right != null){ queue.add(temp.right); } size--; } } return res; } }
222. Count Complete Tree Nodes
- 其实就是后序遍历,加了判断满二叉树的情况
-
java class Solution { public int countNodes(TreeNode root) { if (root == null){ return 0; } //以下是判断满二叉树的停止的情况 int left = 0; int right = 0; TreeNode curLeft = root.left; TreeNode curRight = root.right; while(curLeft != null){ curLeft = curLeft.left; left++; } while(curRight != null){ curRight = curRight.right; right++; } if (left == right){ return (2