lintcode-155-二叉树的最小深度

155-二叉树的最小深度

给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。

样例

给出一棵如下的二叉树:

这个二叉树的最小深度为 2

标签

二叉树 深度优先搜索

思路

LintCode-97.二叉树的最大深度 类似,不同的是在返回左右子树深度时,二叉树的深度必须是根结点到叶子结点的距离,不能单纯的比较左右子树的递归结果返回较小值,因为对于有单个孩子为空的节点,为空的孩子会返回0,但这个节点并非叶子节点,故返回的结果是错误的。
因此,当发现当前处理的节点有单个孩子是空时,返回一个极大值INT_MAX,防止其干扰结果。

code

/**
 * 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 leftDepth = minDepth(root->left);
        int rightDepth = minDepth(root->right);

        leftDepth = (leftDepth == 0 ? INT_MAX : leftDepth);
        rightDepth = (rightDepth == 0 ? INT_MAX : rightDepth);
        
        return (leftDepth < rightDepth) ? (leftDepth + 1) : (rightDepth + 1);
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7260159.html