Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Solution:
1. Recursive:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return getDepth(root, 1);
}
public int getDepth(TreeNode node, int depth) {
int left = depth, right = depth;
if(node.left != null) left = getDepth(node.left, depth + 1);
if(node.right != null) right = getDepth(node.right, depth + 1);
return left > right ? left : right;
}
}
2. Non-recursive:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
// Non-recursive, use level order triversal
ArrayList<TreeNode> q = new ArrayList<TreeNode>();
q.add(root);
int depth = 0;
while(!q.isEmpty()) {
ArrayList<TreeNode> next = new ArrayList<TreeNode>();
for(TreeNode node : q) {
if(node.left != null) next.add(node.left);
if(node.right != null) next.add(node.right);
}
q = new ArrayList<TreeNode>(next);
depth++;
}
return depth;
}
}
good blog, how was your interview?
ReplyDeleteHello,
ReplyDeleteI have tried your recursive solution in the leetcode, but instead of the depth + 1, I have used depth++ or ++depth, but the tests are failing and I do not understand why neither of them are equivalent.