leetcode - Minimum Depth of Binary Tree
2013-11-05 22:56 张汉生 阅读(125) 评论(0) 编辑 收藏 举报
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void minDepth(TreeNode * node, int & minDep, int curDepth){ 13 if (curDepth>=minDep) 14 return; 15 if (node==NULL) 16 return; 17 if (node->left==NULL && node->right==NULL){ 18 minDep = curDepth; 19 } 20 if (node->left != NULL) 21 minDepth(node->left, minDep, curDepth+1); 22 if (node->right != NULL) 23 minDepth(node->right, minDep, curDepth+1); 24 } 25 int minDepth(TreeNode *root) { 26 // IMPORTANT: Please reset any member data you declared, as 27 // the same Solution instance will be reused for each test case. 28 if (root==NULL) 29 return 0; 30 const int maxNum = 1000000000; 31 int minDep = maxNum; 32 minDepth(root, minDep, 1); 33 return minDep; 34 } 35 };