/**
* 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) {
return maxDep(root, 0);
}
public int maxDep(TreeNode node, int dep) {
if (node == null) return dep;
TreeNode rTree = node.left;
TreeNode lTree = node.right;
if (rTree == null && lTree == null) return dep+1;
if (rTree == null)
return maxDep(lTree, dep+1);
if (lTree == null)
return maxDep(rTree, dep+1);
int ldep = maxDep(lTree, dep+1);
int rdep = maxDep(rTree, dep+1);
return (ldep > rdep) ? ldep : rdep;
}
}
Friday, March 28, 2014
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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment