/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcmaxDepth(root *TreeNode) int {if root ==nil {return0 }returnmax(maxDepth(root.Left), maxDepth(root.Right)) +1}funcmax(x, y int) int {if x > y {return x }return y}
Solution 2 (Java)
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */publicclassSolution { /** * @param root: The root of binary tree. * @return: An integer */publicintmaxDepth(TreeNode root) {if (root ==null) return0;returnMath.max(maxDepth(root.left),maxDepth(root.right)) +1; }}
Notes
Recursion with divide and conquer
Solution 3 (Java)
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */publicclassSolution {int maxDepth =0; /** * @param root: The root of binary tree. * @return: An integer */publicintmaxDepth(TreeNode root) {maxDepthHelper(root,1);return maxDepth; }privatevoidmaxDepthHelper(TreeNode root,int depth) {if (root ==null) return;if (depth > maxDepth) maxDepth = depth;maxDepthHelper(root.left, depth +1);maxDepthHelper(root.right, depth +1); }}