• Leetcode 104. Maximum Depth of Binary Tree(二叉树的最大深度)


    Given a binary tree, find its maximum depth.

    The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    分析:求二叉树的最大深度

    解法一:很容易想到的便是递归(深度优先搜索)

    (1)如果根节点是空,则返回0;否则转到(2)

       (2)  l = 左子树的最大深度; r = 右子树的最大深度; 返回  max(l, r) + 1;

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int maxDepth(TreeNode* root) {
    13         if(root == NULL)
    14             return 0;
    15         int l = maxDepth(root->left);
    16         int r = maxDepth(root->right);
    17         return max(l, r) + 1;
    18     }
    19 };


    解法二:我觉得还可以用广度优先搜索:第i层如果存在节点不为空,则深度加1...最大深度就是这棵树的层数。

     1 class Solution {
     2 public:
     3     int maxDepth(TreeNode* root) {
     4         if(root == NULL)
     5             return 0;
     6         int depth = 0;
     7         queue<TreeNode*> node_que;
     8         TreeNode* temp;
     9         node_que.push(root);
    10         while(!node_que.empty()){
    11             int size = node_que.size();
    12             while(size--){
    13                 temp = node_que.front();
    14                 node_que.pop();
    15                 if(temp->left != NULL)
    16                     node_que.push(temp->left);
    17                 if(temp->right != NULL)
    18                     node_que.push(temp->right);
    19             }
    20             depth++;
    21         }
    22         return depth;
    23         
    24     }
    25 };
  • 相关阅读:
    Python_离线包下载地址
    JMeter_简单控制线程组(Thread Group)组件的执行顺序
    Python_pkgutil.walk_packages_查询包下所有文件
    Grafana_数据可视化工具
    Python_dir+getattr_获取模块下所有属性对象
    Jmeter_BeanShell Assertion自定义断言
    python连接数据库及使用
    python题目
    div 内容超出部分隐藏
    在C#类库中使用App.config文件自定义配置
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5723678.html
Copyright © 2020-2023  润新知