Wednesday, May 8, 2013

minimum depth of binary tree(c++ code)

LeetCode Minimum Depth of Binary Tree, Oct 10 '121893 / 4635
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 minDepth(TreeNode *root) {  
  2.        if(!root) return 0;  
  3.        if(!root->left && !root->right) return 1;  
  4.        int leftmin = INT_MAX, rightmin = INT_MAX;  
  5.        if(root->left){  
  6.           leftmin = minDepth(root->left);  
  7.        }  
  8.        if(root->right){  
  9.            rightmin = minDepth(root->right);  
  10.        }  
  11.        return min(leftmin, rightmin) + 1;  
  12.          
  13.    }  

No comments:

Post a Comment