• 104. Maximum Depth of Binary Tree


    1. 问题描述

    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.
    Tags: Tree Depth-first Search
    Similar Problems: (E) Balanced Binary Tree (E) Minimum Depth of Binary Tree
    /**
    * Definition for a binary tree node.
    * struct TreeNode {
    * int val;
    * TreeNode *left;
    * TreeNode *right;
    * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    * };
    */

    2. 解题思路

    • 可以利用递归方式实现,但在LeetCode上运行超时,考虑使用循环方式实现
    • 利用队列,逐层计算:

    3. 代码

     1 class Solution {
     2 public:
     3     //非递归方法(利用队列实现)
     4     int maxDepth(TreeNode* root) 
     5     {
     6         if (NULL == root)
     7         {
     8             return 0;
     9         }
    10         std::queue<TreeNode *> tQue;
    11         tQue.push(root);
    12         int ndepth = 0;
    13         while (!tQue.empty())
    14         {
    15             ndepth++;
    16             int nSize = tQue.size();            
    17             for (int i=0; i<nSize; i++)
    18             {
    19                 TreeNode *pCur = tQue.front();
    20                 tQue.pop();
    21                 if (NULL != pCur->left)
    22                 {
    23                     tQue.push(pCur->left);
    24                 }
    25                 if (NULL != pCur->right)
    26                 {
    27                     tQue.push(pCur->right);
    28                 }
    29             }
    30         }
    31         return ndepth;
    32     }
    33     //递归实现(运行时间超时)
    34     int maxDepth_1(TreeNode* root) 
    35     {
    36         if (NULL == root)
    37         {
    38             return 0;
    39         }
    40         return 1+(maxDepth(root->left)>maxDepth(root->right) ? maxDepth(root->left):maxDepth(root->right));
    41     }
    42 };

    4. 反思

    •  思路类似树的广度优先遍历
  • 相关阅读:
    [BZOJ] 2054 疯狂的馒头
    day33(sql)
    day32(表单校验js和jquery表单校验)
    day31(正则表达式)
    day30(对象转json(java))
    day29(对象转xml(使用java))
    day28(ajax之js原生代码实现)
    day27(反射之内省机制实现BeanUtils)
    day27(反射之内省机制)
    day26(分页查询)
  • 原文地址:https://www.cnblogs.com/whl2012/p/5596695.html
Copyright © 2020-2023  润新知