Minimum Depth of Binary Tree

来源:互联网 发布:ysbn免费网络 编辑:程序博客网 时间:2024/05/21 03:25

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;        int left = minDepth(root->left);        int right = minDepth(root->right);        if(!root->left || !root->right)        return (left < right ? right : left) + 1;        else         return (left < right ? left : right) + 1;    }};

结点的某个孩子结点为空的时候,那么经由该空孩子肯定到达不了叶子结点,那么只能是返回较大值了,当左右都可达时,那就返回较小值了。

0 0
原创粉丝点击