题目描述:
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.
一看到这个题目的时候,想一层一层的数一下,仔细一想貌似不太靠谱,要么改结点结构,要么把结点在第几层存到另外的数据结构中。再一想其实很简单,就像一个递归定义:
当前树的minimum depth等于:
1.左右子树都不为空时,为子树中较小的minimum depth+1;
2.有一个子树为空时,为非空子树的minimum depth+1;
3.都为空时,为1。
这样就可以解决了,时间复杂度为O(n),代码如下:
1 int minDepth(TreeNode *root) { 2 if(root==NULL) return 0; 3 if(root->left==NULL&&root->right==NULL) 4 return 1; 5 6 int rmin=minDepth(root->right); 7 int lmin=minDepth(root->left); 8 if(root->left==NULL) 9 return rmin+1; 10 if(root->right==NULL) 11 return lmin+1; 12 int c = min(lmin,rmin)+1; 13 return c; 14 } 15 int min(int a,int b){ 16 return a<b?a:b; 17 }