1. if it is a leaf node, then return 1.
  2. If left tree is null, then recur to right subtree and vise versa.
  3. if both left and right are not NULL, then return minimum of both heights + 1;
/**
 * 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
        return dfsHelper(root);
    }
    int dfsHelper(TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        int left = dfsHelper(root->left);
        int right = dfsHelper(root->right);
        if (left == 0 && right == 0) {
            return 1;
        } else if (left != 0 && right == 0) {
            return left + 1;
        } else if (left == 0 && right != 0) {
            return right + 1;
        } else {
            return min(left, right) + 1;
        }
    }
};

results matching ""

    No results matching ""