Given the root
of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
가볍게~ 재귀 접근으로 풀었어요. left
와 right
만 비교해도 되고, 한번 재귀 접근할 때마다 +1 하는 식으로 접근하니 해결되었어요.
/**
* 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 {
public int maxDepth(TreeNode root) {
return getDepth(root);
}
private int getDepth(TreeNode node){
if(null == node)
return 0;
return Math.max(getDepth(node.left) + 1, getDepth(node.right) + 1);
}
}