111. Minimum Depth of Binary Tree

来源:互联网 发布:在线播放网站源码 编辑:程序博客网 时间:2024/05/24 04:10

题目

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.


翻译

给定二叉树,找到最小深度。

最小深度是从根节点到最近叶节点的最短路径的节点数。


分析

和找最大距离不同之处在于:找最小距离要注意(l<r)? l+1:r+1的区别应用,因为可能存在左右子树为空的情况,此时值就为0,但显然值是不为0的(只有当二叉树为空才为0)

/** * 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==NULL)       return 0;    int l = minDepth(root->left);     int r = minDepth(root->right);     if (!l)        return r+1;     if (!r)         return l+1;     return (l<r)?l+1:r+1;    }};


0 0