Minimum Depth of Binary Tree

LeetCode #111


Description:

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.

If one Node, depth = 1; If null Node, depth = 0.

Example:

Note

Idea:

Code:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root==NULL) return 0;

        int left_depth=minDepth(root->left);
        int right_depth=minDepth(root->right);

        if(left_depth==0) return right_depth + 1;
        else if(right_depth==0) return left_depth + 1;
        else return min(left_depth, right_depth) + 1; 
    }
};

results matching ""

    No results matching ""