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.
思路:
递归
1 int min(int a, int b){ 2 if(a < b) 3 return a; 4 return b; 5 } 6 int minDepth(TreeNode *root) { 7 // Note: The Solution object is instantiated only once and is reused by each test case. 8 if(root == NULL) 9 return 0; 10 if(root->left == NULL && root->right == NULL) 11 return 1; 12 if(root->left == NULL) 13 return 1+minDepth(root->right); 14 if(root->right == NULL) 15 return 1+minDepth(root->left); 16 return 1+min(minDepth(root->left), minDepth(root->right)); 17 }