LeetCode 111. 二叉树的最小深度*

2022/2/10 23:48:35

本文主要是介绍LeetCode 111. 二叉树的最小深度*,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

基本思想:

广度+dfs可破;

但是注意一下官方的自底向上的思想,不止一次出现过;

自己想了一种判断深度提前剪枝;

具体代码:

提前剪枝:

/**
 * Definition for a binary tree node.
 * 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:
    void dfs(TreeNode* root,int& depth,int dep){
        if(!root->left&&!root->right){
            //叶子结点;
            depth=dep;
            return;
        }
        //超出深度;
        if(dep>=depth)
            return;
        if(root->left)
            dfs(root->left,depth,dep+1);
        if(root->right)
            dfs(root->right,depth,dep+1);
    }

    int minDepth(TreeNode* root) {
        int min_depth=INT_MAX;
        if(!root)
            return 0;
        dfs(root,min_depth,1);
        return min_depth;
    }
};

自底向上递归:

class Solution {
public:
    int minDepth(TreeNode *root) {
        if (root == nullptr) {
            return 0;
        }

        if (root->left == nullptr && root->right == nullptr) {
            return 1;
        }

        int min_depth = INT_MAX;
        if (root->left != nullptr) {
            min_depth = min(minDepth(root->left), min_depth);
        }
        if (root->right != nullptr) {
            min_depth = min(minDepth(root->right), min_depth);
        }

        return min_depth + 1;
    }
};


这篇关于LeetCode 111. 二叉树的最小深度*的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程