자바 이 진 트 리 깊이 구현
1458 단어 검지 offer 알고리즘검지 offer 알고리즘(Java)
코드
해법
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
/**
*
* @param root
* @return
*/
public static int treeDepth(TreeNode root) {
if (root == null) {
return 0;
}
//
int left = treeDepth(root.left);
//
int right = treeDepth(root.right);
// root = + 1
return left >= right ? (left + 1) : (right + 1);
}
해법
public int treeDepth2(TreeNode root) {
if (root == null) {
return 0;
}
int depth = 0;
Stack stack = new Stack<>();
stack.push(root);
while (!root.isEmpty()) {
depth++;
int size = stack.size();
while (size > 0) {
TreeNode current = stack.pop();
if (current.right != null) {
stack.push(current.right);
}
if (current.left != null) {
stack.push(current.left);
}
size--;
}
}
return depth;
}