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.

 

思想:递归即可

注意事项: 如果left或者right为空,需要忽略;

  1. public int minDepth(TreeNode root) {
  2. if(root == null) return 0;
  3. if(root.left == null && root.right == null) return 1;
  4. if(root.left == null) return minDepth(root.right)+1;
  5. if(root.right == null) return minDepth(root.left)+1;
  6. return Math.min(minDepth(root.left),minDepth(root.right))+1;
  7. }

C++代码:

  1. int minDepth(TreeNode *root) {
  2. if(root==NULL) return 0;
  3. int leftmin = minDepth(root->left);
  4. int rightmin = minDepth(root->right);
  5. if(leftmin * rightmin != 0) return min(leftmin,rightmin)+1;
  6. else if(rightmin==0) return leftmin+1;
  7. else if(leftmin==0) return rightmin+1; // notice whether the left tree is null or the right tree is null
  8. }
posted @ 2014-07-29 23:20  purejade  阅读(90)  评论(0编辑  收藏  举报