# Maximum Depth of Binary Tree\_DFS

Given the `root` of a binary tree, return *its maximum depth*.

A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node.

![](https://3269900549-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MIbwNq54Ge4eqsziHM7%2F-MPZD4ODtZqqEtuQ1Xdn%2F-MPZgS2wPWP83u6AFSYU%2Fmaxdepth%20prob%20desc.png?alt=media\&token=d8567a1a-2de7-4e62-a513-affe79c77b59)

자료구조 : Stack

**알고리즘**\
1\. 트리 노드를 루트에서부터 하나씩 스택에 넣는다.\
&#x20;  (노드를 넣는 스택와 깊이 값 넣는 스택, 깊이 값은 root=1부터 시작한다.)\
2\. pop()하면서 왼쪽 자식과 오른쪽 자식이 있으면 push한다.\
3\. 노드 스택에 노드를 넣을 때마다 깊이값은 +1씩 증가한다.\
4\. 깊이 값은 1->2->3->4.. 증가하므로 Math.max(value, max) 로 깊이 값을 비교하며 최댓값을 리턴한다.

```java
/**
 * 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 {//DFS, Stack
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> Vstack = new Stack<>();
        
        stack.push(root);
        Vstack.push(1);//root has 1 depth itself.
        int max = 0;
        while(!stack.isEmpty()) {//till stack is empty, push and pop node and depth value to stack.
            TreeNode node = stack.pop();
            int value = Vstack.pop();
            max = Math.max(max,value);
            if(node.left != null) {
                stack.push(node.left);
                Vstack.push(value+1);
            }
            if(node.right != null) {
                stack.push(node.right);
                Vstack.push(value+1);
            }
        }
        return max;
    }
}
```
