题目
LeetCode 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
|
class Solution { public int maxDepth(TreeNode root) { int depth = 0; if (root == null) { return depth; } List<TreeNode> line = new ArrayList<>(); List<TreeNode> temp; line.add(root); while (!line.isEmpty()) { temp = new ArrayList<>(); for (TreeNode node : line) { if (node.left != null) { temp.add(node.left); } if (node.right != null) { temp.add(node.right); } } line = temp; depth++; } return depth; } }
|
递归解法:
1 2 3 4 5 6 7 8 9 10
| 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; } }
|