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.

分析:

这道题目需要注意,只有在存在左儿子的时候才去找左儿子的深度,否则用INT_MAX替代。不然的话,没有左儿子,左边返回0是不公平的。

解法:

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 = INT_MAX;
        int rightDepth = INT_MAX;
        if (root->left != NULL) {
            leftDepth = minDepth(root->left);
        }
        if (root->right != NULL) {
            rightDepth = minDepth(root->right);
        }
        return min(leftDepth, rightDepth) + 1;
    }
};

results matching ""

    No results matching ""