二叉树的最小深度-LintCode

来源:互联网 发布:管家婆erp是什么软件 编辑:程序博客网 时间:2024/06/06 14:08

给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
这里写图片描述
这个二叉树的最小深度为 2

#ifndef C155_H#define C155_H#include<iostream>using namespace std;class TreeNode{public:    int val;    TreeNode *left, *right;    TreeNode(int val)    {        this->val = val;        this->left = this->right = NULL;    }};class Solution {public:    /**    * @param root: The root of binary tree.    * @return: An integer    */    int minDepth(TreeNode *root) {        // write your code here        if (root == NULL)            return 0;        else            return minDepthRecur(root);         }    int minDepthRecur(TreeNode* node)    {        if (node == NULL)            return INT_MAX;        TreeNode *p =node;        if (p->left == NULL&&p->right == NULL)            return 1;        else        {            return minVal(minDepthRecur(p->left), minDepthRecur(p->right)) + 1;        }    }    int minVal(int a, int b)    {        return a < b ? a : b;    }};#endif
原创粉丝点击