Maximum Depth of Binary Tree

2014.1.7 23:26

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.

Solution:

  depth(tree)  = max(depth(left subtree), depth(right subtree)) + 1;

  depth(nullptr) = 0;

  Time complexity is O(n), where n is the number of nodes in the tree. Space complexity is O(1).

Accepted code:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxDepth(TreeNode *root) {
13         // Note: The Solution object is instantiated only once and is reused by each test case.
14         if(root == NULL){
15             return 0;
16         }else{
17             return 1 + mymax(maxDepth(root->left), maxDepth(root->right));
18         }
19     }
20 private:
21     const int &mymax(const int &a, const int &b) {
22         return (a > b ? a : b);
23     }
24 };

 

 posted on 2014-01-08 00:05  zhuli19901106  阅读(128)  评论(0编辑  收藏  举报