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.
Use a recursive call. The maximum depth is the maximum depth of its left subtree and right subtree plus 1.
C++ Code:
/*
* func: max_depth
* goal: find the max depth of the given binary tree
* @param root: root node of the tree
* return: maximum depth
*/
int max_depth(TreeNode *root){
if(root == nullptr){
return 0;
}
else{
return std::max(max_depth(root->left), max_depth(root->right)) + 1;
}
}
Python Code:
# func: find the maximum depth of binary tree
# @param root: root node of the tree
# @return: maximum depth
def max_depth(root):
if not root:
return 0
else:
return max(max_depth(root.left), max_depth(root.right)) + 1
No comments:
Post a Comment