二叉树的最小深度

来源:互联网 发布:java什么叫并发 编辑:程序博客网 时间:2024/04/30 12:01

题目描述
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.

最小深度需要考虑到是否某个子树深度为0,如果有个节点某个子树为0,就要返回左右子树中深度的最大值,而不是最小值。

class Solution {public:    int run(TreeNode *root) {        if(root==NULL)            return 0;        int left=run(root->left);        int right=run(root->right);        if(left==0||right==0)            return 1+left+right;        return 1+min(left,right);    }};
0 0