void recursion(struct TreeNode* root, int* minDeep, int curDeep){ curDeep++; if (curDeep>=*minDeep) return; if (!root->left && !root->right) { if (curDeep<*minDeep) *minDeep=curDeep; return; } if (root->left) recursion(root->left,minDeep,curDeep); if (root->right) recursion(root->right,minDeep,curDeep); } int minDepth(struct TreeNode* root){ if (!root) return 0; int minDeep=100000; recursion(root,&minDeep,0); return minDeep; }
#define min(A, B) ((A) < (B) ? (A) : (B)) int minDepth(struct TreeNode* root){ if (root == NULL) { return 0; } int left = minDepth(root->left); int right = minDepth(root->right); return (left && right) ? min(left, right) + 1 : left + right + 1; }