Leetcode:Minimum Depth of Binary Tree 二叉树的最短路径

Minimum Depth of Binary Tree

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.

 

解题分析:

二叉树必然递归,这题思路很简单的,就是有个地方很隐蔽

例如 12# 的最短路径长度是2,不是1,因为根节点1的右子树为空,即为空的子树不能参与计算

我们将为空的子树路径长度设为 INT_MAX,那么 使用std::min时就相当于忽略了 为空子树的路径

class Solution {
public:
    int minDepth(TreeNode *root) {
        return minDepth(root, false);
    }
    int minDepth(TreeNode* root, bool hasBother) {
        if (root == NULL) return hasBother == true ? INT_MAX : 0;
        return 1 + std::min(minDepth(root->left, root->right != NULL), minDepth(root->right, root->left != NULL));
    }
};

 

你可能感兴趣的:(LeetCode)