LintCode:二叉树的最小深度

Lintcode : 二叉树的最小深度

给定一个二叉树,找出其最小深度。

二叉树的最小深度为根节点到最近叶子节点的距离。

与二叉树的最大深度不同,不能单纯地使用递归,因为二叉树的深度必须是根结点到叶子结点的距离,不能单纯的比较左右子树的递归结果返回较小值,因为对于有单个孩子为空的节点,为空的孩子会返回0,但这个节点并非叶子节点,故返回的结果是错误的。

因此,当发现当前处理的节点有单个孩子是空时,返回一个极大值INT_MAX,防止其干扰结果。


/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */
class Solution {
public:
    /** * @param root: The root of binary tree. * @return: An integer */
    int minDepth(TreeNode *root) {
        // write your code here
        if (root == NULL) return 0;
        if (root->left == NULL && root->right == NULL) return 1;
        int m = minDepth(root->left) + 1;
        int n = minDepth(root->right) + 1;

        m = (m == 1 ? INT_MAX : m);
        n = (n == 1 ? INT_MAX : n);

        return m < n ? m : n ;
    }
};

参考资料

你可能感兴趣的:(递归,二叉树,lintcode)