递归算法:

1 int maxDepth(TreeNode *root)
2 {
3     return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
4 }

非递归算法(层次遍历基础上设置计数器)

 1 int maxDepth(TreeNode *root)
 2 {
 3     if(root == NULL)
 4         return 0;
 5     
 6     int res = 0;
 7     queue<TreeNode *> q;
 8     q.push(root);
 9     while(!q.empty())
10     {
11         ++ res;
12         for(int i = 0, n = q.size(); i < n; ++ i)
13         {
14             TreeNode *p = q.front();
15             q.pop();
16             
17             if(p -> left != NULL)
18                 q.push(p -> left);
19             if(p -> right != NULL)
20                 q.push(p -> right);
21         }
22     }
23     
24     return res;
25 }

 

posted on 2018-04-18 10:03  高数考了59  阅读(227)  评论(0)    收藏  举报