LeetCode104.二叉树的最大深度

题目

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

第5行还不清楚为什么会超时?条件运算符要慢?

法二、用层次遍历的思想也要会

 1 class Solution {
 2 public:
 3     int maxDepth(TreeNode* root) {
 4         if(root == NULL) return 0;
 5         queue<TreeNode*> q;
 6         q.push(root);
 7         int depth = 0;
 8         while(!q.empty()) {
 9             int num = q.size();
10             while(num > 0){
11                 TreeNode *p = q.front();q.pop();
12                 if(p->left != NULL) q.push(p->left);
13                 if(p->right != NULL) q.push(p->right);
14                 num--;
15             }
16             depth++;
17         }
18         return depth;
19     }
20 };
原文地址:https://www.cnblogs.com/fresh-coder/p/14223023.html