leetcode 104. Maximum depth of a binary tree

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 .

 

Ideas:

  Using recursive thinking

1 class Solution {
2 public:
3     int maxDepth(TreeNode* root) {
4         if(root == NULL) return 0;
5         int l = maxDepth(root->left)+1;
6         int r = maxDepth(root->right)+1;
7         return l > r ? l : r;
8     }
9 };

 

Guess you like

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