zoukankan      html  css  js  c++  java
  • 【Leetcode】【Easy】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.

    递归解题思路:

    ①结点为空时,返回0;②当前结点的深度 = max(两个孩子结点各自最大深度)+ 1

     1 /**
     2  * Definition for binary tree
     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) 
    14             return 0;
    15         
    16         return max(maxDepth(root->left), 
    17                 maxDepth(root->right)) + 1;
    18     }
    19 };

    迭代的解法:

    用queue先进先出的特性,按层遍历,最后返回遍历的层数。

     1 class Solution {
     2 public:
     3     int maxDepth(TreeNode *root) {
     4         if (!root) {
     5             return 0;
     6         }
     7         
     8         queue<TreeNode *> nodeQue;
     9         nodeQue.push(root);
    10         int levelNodesCnt;
    11         int depth = 0;
    12         
    13         while (!nodeQue.empty()) {
    14             depth++;
    15             levelNodesCnt = nodeQue.size();
    16             while (levelNodesCnt--) {
    17                 if (nodeQue.front()->left)
    18                     nodeQue.push(nodeQue.front()->left);
    19                 if (nodeQue.front()->right)
    20                     nodeQue.push(nodeQue.front()->right);
    21                 nodeQue.pop();
    22             }
    23         }
    24         
    25         return depth;
    26     }
    27 };

    附录:

    C++ queue使用

  • 相关阅读:
    表字段出现oracle sql语句关键字时
    使用decode函数
    PL/SQL DEVELOPER 使用小技巧
    Linux静态IP设置修改配置文件
    在idea上使用maven搭建ssm,数据库为mysql
    作业
    SQL 简单的生成xml
    使用CppUnit
    tinyXml的使用
    NSIS 使用技巧
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4127452.html
Copyright © 2011-2022 走看看