Leetcode / 104. Maximum Depth of Binary Tree
Pick a programming language:
Here is the source code for the solution to this problem.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int traverse(TreeNode root, int depth) {
if (root == null) {
return depth;
}
int leftDepth = traverse(root.left, depth + 1);
int rightDepth = traverse(root.right, depth + 1);
return Math.max(leftDepth, rightDepth);
}
public int maxDepth(TreeNode root) {
return traverse(root, 0);
}
}
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: