LeetCode problem#104
Maximum Depth of Binary Tree
Solved in 1 languageJava
Solution
30 lines
1/**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 * int val;
5 * TreeNode left;
6 * TreeNode right;
7 * TreeNode() {}
8 * TreeNode(int val) { this.val = val; }
9 * TreeNode(int val, TreeNode left, TreeNode right) {
10 * this.val = val;
11 * this.left = left;
12 * this.right = right;
13 * }
14 * }
15 */
16class Solution {
17 private int traverse(TreeNode root, int depth) {
18 if (root == null) {
19 return depth;
20 }
21
22 int leftDepth = traverse(root.left, depth + 1);
23 int rightDepth = traverse(root.right, depth + 1);
24
25 return Math.max(leftDepth, rightDepth);
26 }
27 public int maxDepth(TreeNode root) {
28 return traverse(root, 0);
29 }
30}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.