Maximum Depth of Binary Tree_DFS
DFS, Stack

Last updated
DFS, Stack

Last updated
/**
* 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;
}
}