The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
要判斷該root是不是leaf
因為值接回傳return le>=ri 會變成 不是leaf的誤判(右子樹沒東西 會回傳0 一定最小)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int minDepth(struct TreeNode* root) { if(root==NULL)return 0; int le=minDepth(root->left); int ri=minDepth(root->right); if(root->left && root->right ) return le>=ri? ri+1:le+1; else if(root->left)return le+1; else return ri+1; } |
沒有留言:
張貼留言