문제 링크: https://leetcode.com/problems/maximum-depth-of-binary-tree/
Binary tree의 root가 주어지면, 해당 트리의 높이를 반환하는 문제이다.
tree를 순회하는 방법은 1. 재귀적 방법과, 2. Stack을 이용한 반복적 방법이 있다.
Binary tree의 최대 높이는 root node로부터 leaf node까지의 최장 거리이다.
정의에 따라 tree를 traverse하면서, leaf node까지의 최장 거리를 계산하면 된다.
재귀적으로 tree의 높이를 반환한다.
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
}
}
Stack을 이용해 위의 recursion을 iteration으로 변환할 수 있다.
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
int depth = 0;
queue.offer(root);
while(!queue.isEmpty()) {
int size = queue.size();
for(int i=0; i<size; i++) {
TreeNode currNode = queue.poll();
if(currNode.left != null) queue.offer(currNode.left);
if(currNode.right != null) queue.offer(currNode.right);
}
depth++;
}
return depth;
}
}