【算法与数据结构】104、111、LeetCode二叉树的最大/最小深度

所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解

一、题目

在这里插入图片描述
在这里插入图片描述

二、层序遍历法

  思路分析:两道题都可以用层序遍历(迭代法)来做,遍历完一层深度变量depth就++。找最小深度实际上等价于找离根节点最近的叶子节点,我们在遍历每一个节点时,判断它的左右节点是否为空,若为空则为叶子节点,输出此时的depth。
  找最大深度程序如下

class Solution {
public:
    // 找最大深度
	int maxDepth(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        int Depth = 0, size = 0;    // 根节点深度定义为1
        while (!que.empty()) {
            Depth++;
            size = que.size();      // size必须固定, que.size()是不断变化的
            for (int i = 0; i < size; ++i) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }            
        }
        return Depth;
	}
};

  找最小深度程序如下

class Solution2 {
public:
    // 找最小深度
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        queue<TreeNode*> que;
        que.push(root);
        int Depth = 0, size = 0;    // 根节点深度定义为1
        while (!que.empty()) {
            Depth++;
            size = que.size();      // size必须固定, que.size()是不断变化的
            for (int i = 0; i < size; ++i) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left == NULL && node->right == NULL) return Depth;
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return Depth;
    }
};

三、递归法

  当然,这道题也可以用递归法实现。一般的递归法我们需要注意三个点:

  • 1、输入参数和返回值
  • 2、确定终止条件
  • 3、确定单层递归逻辑
      找最大深度程序如下,程序当中终止条件为节点为NULL,返回0,表示深度为0。依次寻找左右节点的深度,然后当前节点的最大深度为左右节点最大值+1(+1是因为算上当前中间节点)。
class Solution3 {
public:
    // 找最大深度
    int getDepth(TreeNode* root) {
        if (!root) return 0;
        int leftdepth = getDepth(root->left);
        int rightdepth = getDepth(root->right);
        int depth = 1 + max(leftdepth, rightdepth);
        return depth;
    }
    int maxDepth(TreeNode* root) {
        return getDepth(root);
    }
};

  精简版本如下

class Solution3 {
public:
    // 递归法找最大深度,简化版
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};

四、完整代码

# include <iostream>
# include <vector>
# include <queue>
# include <string>
# include <algorithm>
using namespace std;

// 树节点定义
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    // 找最大深度
	int maxDepth(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        int Depth = 0, size = 0;    // 根节点深度定义为1
        while (!que.empty()) {
            Depth++;
            size = que.size();      // size必须固定, que.size()是不断变化的
            for (int i = 0; i < size; ++i) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }            
        }
        return Depth;
	}
};

class Solution2 {
public:
    // 找最小深度
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        queue<TreeNode*> que;
        que.push(root);
        int Depth = 0, size = 0;    // 根节点深度定义为1
        while (!que.empty()) {
            Depth++;
            size = que.size();      // size必须固定, que.size()是不断变化的
            for (int i = 0; i < size; ++i) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left == NULL && node->right == NULL) return Depth;
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return Depth;
    }
};

//class Solution3 {
//public:
//    // 递归法找最大深度
//    int getDepth(TreeNode* root) {
//        if (!root) return 0;
//        int leftdepth = getDepth(root->left);
//        int rightdepth = getDepth(root->right);
//        int depth = 1 + max(leftdepth, rightdepth);
//        return depth;
//    }
//    int maxDepth(TreeNode* root) {
//        return getDepth(root);
//    }
//};

class Solution3 {
public:
    // 递归法找最大深度,简化版
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};

void my_print(vector <string>& v, string msg)
{
    cout << msg << endl;
    for (vector<string>::iterator it = v.begin(); it != v.end(); it++) {
        cout << *it << "  ";
    }
    cout << endl;
}

// 前序遍历迭代法创建二叉树,每次迭代将容器首元素弹出(弹出代码还可以再优化)
void Tree_Generator(vector<string>&t, TreeNode* &node) {
    if (t[0] == "NULL" || !t.size()) return;    // 退出条件
    else {
        node = new TreeNode(stoi(t[0].c_str()));    // 中
        t.assign(t.begin() + 1, t.end());
        Tree_Generator(t, node->left);              // 左
        t.assign(t.begin() + 1, t.end());
        Tree_Generator(t, node->right);             // 右
    }
}

int main()
{
    vector<string> t = { "3", "9", "NULL", "NULL", "20", "15", "NULL", "NULL", "7", "NULL", "NULL"};   // 前序遍历
    my_print(t, "目标树");
    TreeNode* root = new TreeNode();
    Tree_Generator(t, root);
    Solution3 s1;
    int result = s1.maxDepth(root);
    cout << "最大深度为:" << result << endl;
	system("pause");
	return 0;
}

end

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚安66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值