LeetCode - Maximum depth of a binary tree

Solve it by yourself, welcome to Paizhuan

Given a binary tree, find its maximum depth.

The depth of a binary tree is the number of nodes on the longest path from the root node to the farthest leaf node.

Explanation: A leaf node is a node that has no child nodes.

Example:
Given a binary tree  [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

Returns its maximum depth of 3 .

 

solution:

 1 int maxDepth(struct TreeNode* root) 
 2 {
 3         if (root == NULL)
 4             return 0;
 5         if (root->left == NULL && root->right == NULL)
 6             return 1;
 7          
 8         int leftHeight = maxDepth(root->left);
 9         int rightHeight = maxDepth(root->right);
10     
11         return (leftHeight > rightHeight) ? leftHeight+1 : rightHeight+1;
12 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324832847&siteId=291194637