第十八周:[Leetcode]111. Minimum Depth of Binary Tree

来源:互联网 发布:淘宝排除王 编辑:程序博客网 时间:2024/06/05 14:57

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.


和求最大距离不一样,因为是求到叶子节点的最小距离,需要区分左右子树有可能为空的情况。


class Solution {public:    int minDepth(TreeNode* root) {        if(root == NULL)            return 0;        if(root -> left == NULL && root -> right == NULL)            return 1;        if(root -> left != NULL && root -> right == NULL)            return minDepth(root -> left) + 1;        if(root -> left == NULL && root -> right != NULL)            return minDepth(root -> right) + 1;        return min(minDepth(root -> left) + 1,minDepth(root -> right) + 1);    }};
原创粉丝点击