111:Minimum Depth of Binary Tree【树】【DFS】

来源:互联网 发布:淘宝菜鸟驿站没有了 编辑:程序博客网 时间:2024/06/06 05:31

题目链接:click~

/*题意:求二叉树的最小深度(从根结点到最近的叶子结点)*//** *思路:DFS遍历整个树,只需要叶子结点的到根的距离 * */struct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:    int minDepth(TreeNode *root) {        if(root == NULL) return 0;        if(root->left == NULL && root->right == NULL) return 1;//叶子结点        int LeftDepth = minDepth(root->left);  //左子树的最小深度        int RightDepth = minDepth(root->right);//右子树的最小深度        if(LeftDepth == 0) //非叶子结点且左子树为空            return RightDepth + 1;        else if(RightDepth == 0) //非叶子结点且右子树为空            return LeftDepth + 1;        else            return min(LeftDepth, RightDepth) + 1;    }};


0 0