이진트리에서, 가장 깊은 depth를 구하는 문제이다.
public static int getHeight(Node root){
int maxHeight = 0;
int right = 0;
int left = 0;
if(root.left==null&&root.right==null){
return 0;
}else{
if(root.left==null){
right = 1+getHeight(root.right);
}else if(root.right==null){
left = 1+getHeight(root.left);
}else{
left = 1+getHeight(root.left);
right = 1+getHeight(root.right);
}
maxHeight = right>left?right:left;
}
return maxHeight;
}
재귀로 풀면 편할 것 같아서, 몇번 오답내고 풀어서 좋아했는데
private static int getHeight(Node root){
int heightLeft = 0;
int heightRight = 0;
if (root.left != null) {
heightLeft = getHeight(root.left) + 1;
}
if (root.right != null) {
heightRight = getHeight(root.right) + 1;
}
return (heightLeft > heightRight ? heightLeft : heightRight);
}
if조건을 더 폭넓게 해서 else문을 하나 뺄 수가 있었다.