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 { private: int mindepth; public: void tra(TreeNode* root,int depth){ if(root==NULL) return; ++depth; if(!root->left&&!root->right&&depth!=1&&depth<mindepth)//必须是叶节点才更新mindepth mindepth=depth; tra(root->left,depth); tra(root->right,depth); } int minDepth(TreeNode *root) { mindepth=65535; if(!root) return 0; if(root->left==NULL&&root->right==NULL) return 1; tra(root,0); if(mindepth==65535){ return 0; } return mindepth; } };