leetcode1Minimum Depth of Binary Tree

题目描述

求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
示例1

输入

复制
{1,2,3,4,5}

输出

复制
2

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    int run(TreeNode* root) {
        // write code here
        if (root==nullptr) return 0;
        if (root->left == nullptr)
        {
            return run(root->right) +1;
            
        }
        if (root->right == nullptr)
        {
            return run(root->left)+1;
            
        }
        int leftDepth=run(root->left);
        int rightDepth=run(root->right);
        return (leftDepth <rightDepth) ?(leftDepth+1):(rightDepth+1);
    }
    
};

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    typedef TreeNode *tree;
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    int run(TreeNode* root) {
        // write code here
        if (!root) return 0;
        queue <tree> qu;
        tree last,now;
        int level,size;
        last=now=root;
        level=1;qu.push(root);
        while (qu.size()){
            now=qu.front();
            qu.pop();
            size=qu.size();
            if (now->left) qu.push(now->left);
            if (now->right) qu.push(now->right);
            if (qu.size()-size==0) break;
            if (last==now){
                level++;
                if (qu.size()) last=qu.back();
                
            }
        }
        return level;
        
    }
};

原文地址:https://www.cnblogs.com/hrnn/p/13438306.html