Leecode 111. 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.
Subscribe to see which companies asked this question
思路: 这道题本来没什么,wa了两次。递归的规则没有把握好。
AC代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int minDepth(TreeNode* root) { if(root == NULL) return 0; if(root ->left == NULL && root->right == NULL) return 1; int ans = 1<<29; if(root->left) { ans = min(ans, minDepth(root->left)); } if(root->right) { ans = min(ans, minDepth(root->right)); } return ans + 1; } };

浙公网安备 33010602011771号