zoukankan      html  css  js  c++  java
  • [剑指Offer] 38.二叉树的深度

    题目描述

    输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

    【思路1】递归

     1 /*
     2 struct TreeNode {
     3     int val;
     4     struct TreeNode *left;
     5     struct TreeNode *right;
     6     TreeNode(int x) :
     7             val(x), left(NULL), right(NULL) {
     8     }
     9 };*/
    10 class Solution {
    11 public:
    12     int TreeDepth(TreeNode* pRoot)
    13     {
    14         if(pRoot == NULL)
    15             return 0;
    16         int h1 = TreeDepth(pRoot->left);
    17         int h2 = TreeDepth(pRoot->right);
    18         return max(h1,h2) + 1;
    19     }
    20 };

     【思路2】DFS,用一个栈来存储结点,一个栈来存储当前深度

     1 /*
     2 struct TreeNode {
     3     int val;
     4     struct TreeNode *left;
     5     struct TreeNode *right;
     6     TreeNode(int x) :
     7             val(x), left(NULL), right(NULL) {
     8     }
     9 };*/
    10 class Solution
    11 {
    12 public:
    13     int TreeDepth(TreeNode* pRoot)
    14     {
    15         if(pRoot == NULL) return 0;
    16         stack<TreeNode*> nodeStack;
    17         stack<int> depthStack;
    18         
    19         nodeStack.push(pRoot);
    20         depthStack.push(1);
    21         
    22         TreeNode* node = pRoot;
    23         int MaxDepth = 0;
    24         int curDepth = 0;
    25         
    26         while(!nodeStack.empty())
    27         {
    28             node = nodeStack.top();
    29             nodeStack.pop();
    30             curDepth = depthStack.top();
    31             depthStack.pop();
    32             if(MaxDepth < curDepth)
    33                 MaxDepth = curDepth;
    34             
    35             if(node->left != NULL)
    36             {
    37                 nodeStack.push(node->left);
    38                 depthStack.push(curDepth + 1);
    39             }
    40             if(node->right != NULL)
    41             {
    42                 nodeStack.push(node->right);
    43                 depthStack.push(curDepth + 1);
    44             }
    45         }
    46         return MaxDepth;
    47     }
    48 };
  • 相关阅读:
    创建一个简单的图片服务器
    spring-boot系列:初试spring-boot
    java的动态代理机制
    jedis连接池详解(Redis)
    使用logback.xml配置来实现日志文件输出
    redis在mac上的安装
    理解RESTful架构
    分布式应用框架Akka快速入门
    [Java基础]Java通配符
    Mac vim iterm2配色方案
  • 原文地址:https://www.cnblogs.com/lca1826/p/6515963.html
Copyright © 2011-2022 走看看