tutorialcup
Maximum Depth of Binary Tree Leetcode Solution
Problem Statement
In the problem a binary tree is given and we have to find out the maximum depth of the given tree. 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.
Example
3
/
9 20
/
15 7
3
Explanation: There are two possible longest path as shown in below tree in red color.
Empty Tree
0
As the tree is empty, depth is 0.
0
1
As there are only one node, depth is 1.
Approach
To find the maximum depth of the tree we can apply a simple recursive approach. Where each function call will represent a subtree which has root node called as 'root'. We traverse the tree by a recursive function starting from the root node.
So the base case is when the subtree is empty i.e. root is NULL. So we return depth as 0.
if root is not NULL, call the same function recursively for its left child and right child.
As shown in figure, when the two child function return its depth we pick the maximum out of these two subtrees and return this value after adding 1 to it ( Adding current node which is the parent of the two subtrees).
Implementation
C++ Program for Maximum Depth of Binary Tree Leetcode Solution
#includ
www.tutorialcup.com/leetcode-solutions/maximum-depth-of-b...
Maximum Depth of Binary Tree Leetcode Solution
Problem Statement
In the problem a binary tree is given and we have to find out the maximum depth of the given tree. 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.
Example
3
/
9 20
/
15 7
3
Explanation: There are two possible longest path as shown in below tree in red color.
Empty Tree
0
As the tree is empty, depth is 0.
0
1
As there are only one node, depth is 1.
Approach
To find the maximum depth of the tree we can apply a simple recursive approach. Where each function call will represent a subtree which has root node called as 'root'. We traverse the tree by a recursive function starting from the root node.
So the base case is when the subtree is empty i.e. root is NULL. So we return depth as 0.
if root is not NULL, call the same function recursively for its left child and right child.
As shown in figure, when the two child function return its depth we pick the maximum out of these two subtrees and return this value after adding 1 to it ( Adding current node which is the parent of the two subtrees).
Implementation
C++ Program for Maximum Depth of Binary Tree Leetcode Solution
#includ
www.tutorialcup.com/leetcode-solutions/maximum-depth-of-b...