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
|
private static int maxDepth2(TreeNode root) { if (root == null) { return 0; } LinkedList<Pair<TreeNode, Integer>> stack = new LinkedList<>(); stack.push(new Pair<>(root, 1)); int maxDepth = 0; while (!stack.isEmpty()) { Pair<TreeNode, Integer> pair = stack.pop(); TreeNode node = pair.first; maxDepth = Math.max(maxDepth, pair.second); int curDepth = pair.second; if (node.right != null) { stack.push(new Pair<>(node.right, curDepth + 1)); } if (node.left != null) { stack.push(new Pair<>(node.left, curDepth + 1)); } } return maxDepth; }
|