Lintcode:ツリーの最小深さ

2323 ワード

質問:
ツリーに最小深さを指定します.
ツリーの最小深さは、ルートノードから最も近いリーフノードへの最短パスのノード数です.
サンプル:
例1:
  : {}
  : 0

例2:
  :  {1,#,2,3}
  : 3	
  :
	1
	 \ 
	  2
	 /
	3    
        {1,#,2,3}

例3:
  :  {1,2,3,#,#,4,5}
  : 2	
  : 
      1
     / \ 
    2   3
       / \
      4   5  
        {1,2,3,#,#,4,5}

python:
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: The root of binary tree
    @return: An integer
    """
    def minDepth(self, root):
        # write your code here
        if root == None:
            return 0
        else:
            lnum = self.minDepth(root.left)
            rnum = self.minDepth(root.right)
            if root.left == None or root.right == None:
                if root.left == root.right:
                    return 1
                elif root.left != None:
                    return lnum+1
                else:
                    return rnum+1
            else:
                return min(lnum, rnum)+1

C++:
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of binary tree
     * @return: An integer
     */
    int minDepth(TreeNode * root) {
        // write your code here
        if(root == NULL)
        {
            return 0;
        }else{
            int lnum = minDepth(root->left);
            int rnum = minDepth(root->right);
            if(root->left == NULL || root->right == NULL)
            {
                if(root->left == root->right)
                {
                    return 1;
                }else if(root->left != NULL)
                {
                    return lnum+1;
                }else{
                    return rnum+1;
                }
            }else{
                return min(lnum,rnum)+1;
            }
        }
        
    }
};