二叉树的最大深度

题目描述

image.png

题解

使用递归,二叉树的最大深度是其左子树和右子树最大深度的最大值再加一

C++中得到两个数a和b中的最大值可以直接使用max(a, b)

代码

// maxDepth.cpp
#include <iostream>

using namespace std;

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x): val(x), left(NULL), right(NULL){}
    ~TreeNode(){
        if (this->left != NULL){
            delete this->left;
            this->left = NULL;
        }
        if (this->right != NULL){
            delete this->right;
            this->right = NULL;
        }
    }
};


class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int maxDepth(TreeNode* root) {
        // write code here
        if (root == NULL){
            return 0;
        }
        else{
            return max(maxDepth(root->left), maxDepth(root->right)) + 1;
        }
    }
};

int main(){
    TreeNode* root = new TreeNode(1);
    root->left = new TreeNode(2);
    Solution s;
    cout << s.maxDepth(root) << endl;
    delete root;
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容