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.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int minDepth(TreeNode *root) { vector<int> depth; if(root==NULL) return 0; calc(root, depth, 0); int min = depth[0]; int len = depth.size(); for(int i=1;i<len;i++){ if(depth[i]<min) min = depth[i]; } return min; } void calc(TreeNode *root, vector<int> &depth, int crt){ if(root->left==NULL && root->right==NULL){ depth.push_back(crt+1); return; } if(root->left) calc(root->left, depth, crt+1); if(root->right) calc(root->right, depth, crt+1); } };
浙公网安备 33010602011771号