zoukankan      html  css  js  c++  java
  • 剑指offer:二叉树的深度

    题目描述:

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

    解题思路:

    这道题也是递归的思路,比较简单。

    做的过程中遇到的一个问题是return count++这句,实际返回的是count之后再加了。还是直接用count+1返回。

    代码:

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };*/
    class Solution {
    public:
        int TreeDepth(TreeNode* pRoot)
        {
            if(pRoot==nullptr)
                return 0;
            int count=0;
            if(pRoot->left==nullptr && pRoot->right==nullptr)
                return count+1;
            count++;
            return count+max(TreeDepth(pRoot->left), TreeDepth(pRoot->right));
        
        }
    };
  • 相关阅读:
    matlab2016b和c# .net4.0混合编程
    有限元入门
    math.net 拟合
    excel 错误提示以及其他基础知识
    excel的小bug
    Servlet体系及方法
    Servlet学习笔记
    HTTP协议
    Tomcat
    反射
  • 原文地址:https://www.cnblogs.com/LJ-LJ/p/10604521.html
Copyright © 2011-2022 走看看