zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    Variational Autoencoders and Nonlinear ICA: A Unifying Framework
    各层的特征的差异性
    TriggerBN +
    Exponential family of distributions
    个人加分项
    对老师的建议
    2021.6.19
    2021.6.18
    2021.6.17
    2021.6.16
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14223023.html
Copyright © 2011-2022 走看看