一、“见树用递归”
int maxDepth(struct TreeNode* root){
int left, right;
if(0 == root) return 0;
if(0 == root->left && 0 == root->right) return 1;
left = maxDepth(root->left);
right = maxDepth(root->right);
return 1+(left>right?left:right);
}
时间太久了
二、层序遍历
|
class Solution {
public:
int maxDepth(TreeNode* root) {
int cout =0;
if(root == NULL) return cout;
queue <TreeNode* > q;
q.push(root);
while(!q.empty()) {
int nums = q.size();//用于记录该层有多少个元素
while(nums >0 ) {
TreeNode* temp = q.front();
q.pop();
if(temp->left != NULL) q.push(temp ->left); //左孩子入队
if(temp->right != NULL) q.push(temp ->right); //右孩子入队
nums--;
}
if(nums == 0) cout++; //遍历完该层
}
return cout;
}
};
耗时更短