我新建的个人博客,欢迎访问:hmilzy.github.io
104.二叉树的最大深度 题目链接:二叉树的最大深度
层序遍历和递归都行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 class Solution { public int maxDepth (TreeNode root) { if (root == null ) { return 0 ; } int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return Math.max(leftDepth,rightDepth) + 1 ; } }
559.n叉树的最大深度 题目链接:n叉树的最大深度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 class Solution { public int maxDepth (Node root) { if (root == null ) { return 0 ; } int depth = 0 ; for (Node node : root.children) { depth = Math.max(depth,maxDepth(node)); } return depth + 1 ; } }
111.二叉树的最小深度 题目链接:二叉树的最小深度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 class Solution { public int minDepth (TreeNode root) { if (root == null ) { return 0 ; } int leftDepth = minDepth(root.left); int rightDepth = minDepth(root.right); if (root.left == null ) { return rightDepth + 1 ; } if (root.right == null ) { return leftDepth + 1 ; } return Math.min(leftDepth,rightDepth) + 1 ; } }
222.完全二叉树的节点个数 题目链接:完全二叉树的节点个数
个人认为还是递归法好一点。完全二叉树的方法不太能理解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 class Solution { public int countNodes (TreeNode root) { if (root == null ) return 0 ; TreeNode left = root.left; TreeNode right = root.right; int leftDepth = 0 , rightDepth = 0 ; while (left != null ) { left = left.left; leftDepth++; } while (right != null ) { right = right.right; rightDepth++; } if (leftDepth == rightDepth) { return (2 << leftDepth) - 1 ; } int leftNum = countNodes(root.left); int rightNum = countNodes(root.right); int treeNum = leftNum + rightNum + 1 ; return treeNum; } }