LeetCode - 104. Maximum Depth of Binary Tree
재귀로 풀이.
위 트리를 재귀형태로 풀면 다음과 같은 순서.
maxDepth(3)
LD = maxDepth(9) = 1
maxDepth(9) = 1
LD = maxDepth(null) = 0
maxDepth(null)
return 0;
RD = maxDepth(null)
maxDepth(null)
return 0;
return 1 + Math.max(LD 0 , RD 0) = 1
RD = maxDepth(20) = 2
maxDepth(20) = 2
LD = maxDepth(15) = 1
maxDepth(15) = 1
LD = maxDepth(null) = 0
RD = maxDepth(null) = 0
return 1 + Math.max(LD 0, RD 0);
RD = maxDepth(7) = 1
maxDepth(7) = 1
LD = maxDepth(null) = 0
RD = maxDepth(null) = 0
return 1 + Math.max(LD 0 , RD 0);
return 1 + Math.max(LD 1,RD 1) = 2
return 1 + Math.max(LD 1 , RD 2) = 3
/**
* 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) {
if(root == null) return 0;
int lD = maxDepth(root.left);
int rD = maxDepth(root.right);
return 1 + Math.max(lD, rD);
}
}
iteration으로도 풀어봐야지