@snuffles
2019-04-04T08:22:21.000000Z
字数 741
阅读 942
树
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
解1:深度优先遍历,记录1+max(left,right)
解2:层序遍历,注意是利用queue,和在q.size()里循环
解2:
int maxDepth(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*> q{{root}};
int res = 0;
while(!q.empty()){
++ res;
for(int i=q.size();i>0;i--){
TreeNode *t = q.front();
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return res;
}
解1:记住1+max(maxDepth(root->left),maxDepth(root->right)); time5
int maxDepth(TreeNode* root) {
if(!root) return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
```
原来time 5%,内存0%
int maxDepth(TreeNode* root) {
if( root == NULL){
return 0;
}else{
int left_height = maxDepth(root->left);
int right_height = maxDepth(root->right);
return left_height > right_height ? left_height+1 : right_height+1 ;
}
}
};
```