Leetcode学习笔记(三)树的最大深度

本章从两方面总结:二叉树的最大深度和N叉树的最大深度

一.二叉树的最大深度

题目描述

解法一:递归 

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if( root == NULL)
        return 0;

        int left_depth = maxDepth(root -> left) + 1;
        int right_depth = maxDepth(root -> right) + 1;

        if(left_depth >= right_depth)
        return left_depth;
        else
        return right_depth;

        }
};

这种方法容易造成堆栈的溢出。

解法二:DFS(利用堆栈)

#include<stack>
class Solution {
public:
    int maxDepth(TreeNode* root) {
        stack<pair<TreeNode*, int>> s;

        if (root == NULL)
        return 0;
        
        s.push(pair<TreeNode*,int>(root, 1));
        int maxDepth = 1;
        int curDepth = 1;

        while(s.empty() != 1)
        {
            root = s.top().first;
            curDepth = s.top().second;
            s.pop();
            if(curDepth > maxDepth)
            maxDepth = curDepth;
            if (root -> left != NULL)
            {
                s.push(pair<TreeNode*,int>(root -> left, curDepth + 1));
            }
            if (root -> right != NULL)
            {
                s.push(pair<TreeNode*,int>(root -> right, curDepth + 1));
            }
        }
        return maxDepth;
    }
};

知识点普及:

pair是将2个数据组合成一个数据,当需要这样的需求时就可以使用pair。另一个应用是,当一个函数需要返回2个数据的时候,可以选择pair。 pair的实现是一种结构体,主要的两个成员变量是first, second 因为是使用struct不是class,所以可以直接使用pair的成员变量。

下面图帮助理解(摘自小浩算法)

 

方法三:BFS

class Solution {
public:
    int maxDepth(TreeNode* root) {
        queue<pair<TreeNode*, int>> queue;

        if (root == NULL)
        return 0;
        
        queue.push(pair<TreeNode*,int>(root, 1));
        int curDepth = 0;
        int mount;

        while(queue.size() != 0)
        {
            curDepth++;
            mount = queue.size();
            for(int i = 0; i < mount; i++)
            {
                root = queue.front().first;
                queue.pop();
                if(root -> left != NULL)
                queue.push(pair<TreeNode*,int>(root -> left, curDepth));
                if(root -> right != NULL)
                queue.push(pair<TreeNode*,int>(root -> right, curDepth));
            }
        }
        return curDepth;

        
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值