코딩테스트
[leetcode] 104. Maximum Depth of Binary Tree
nayoon
2024. 5. 23. 21:06
/**
* 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 {
static int max;
public int maxDepth(TreeNode root) {
max = 0;
check(root, 0);
return max;
}
public void check(TreeNode node, int cnt) {
if (node == null) {
if (cnt > max) {
max = cnt;
}
return;
}
check(node.left, cnt + 1);
check(node.right, cnt + 1);
}
}
릿코드에서 static을 쓸때는 꼭 시작점에서 한번씩 초기화해줘야함.