[关闭]
@snuffles 2019-04-04T16:22:21.000000Z 字数 741 阅读 899

L104 二叉树的最大深度


给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

解1:深度优先遍历,记录1+max(left,right)
解2:层序遍历,注意是利用queue,和在q.size()里循环

解2:

  1. int maxDepth(TreeNode* root) {
  2. if(!root) return 0;
  3. queue<TreeNode*> q{{root}};
  4. int res = 0;
  5. while(!q.empty()){
  6. ++ res;
  7. for(int i=q.size();i>0;i--){
  8. TreeNode *t = q.front();
  9. q.pop();
  10. if(t->left) q.push(t->left);
  11. if(t->right) q.push(t->right);
  12. }
  13. }
  14. return res;
  15. }

解1:记住1+max(maxDepth(root->left),maxDepth(root->right)); time5

  1. int maxDepth(TreeNode* root) {
  2. if(!root) return 0;
  3. return 1+max(maxDepth(root->left),maxDepth(root->right));
  4. }
  5. ```
  6. 原来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 ;
    }     
}

};
```

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注