leetcode: Minimum Depth of Binary Tree

来源:互联网 发布:论文引用格式网络文章 编辑:程序博客网 时间:2024/06/06 19:29

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.

题目描述:

             求二叉树的最小深度。和求二叉树的最大深度有些区别,仔细看了别人的简洁代码。

代码实现:

/** * Definition for a binary tree node. * 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==0)        {            return 0;        }        int left=minDepth(root->left);        int right=minDepth(root->right);        if(left==0)        {            return right+1;        }        else if(right==0)        {            return left+1;        }        else        {            return min(left,right)+1;        }    }};


1 1
原创粉丝点击