码疯窝

LeetCode 每日一题 — Minimum Depth of Binary Tree

2014/12/12 10:59:09    分类: 日志连载    0人评论 次浏览

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

算法分析: 这道题目与那道 Maximum Depth of Binary Tree 基本一样, 但因为是求最小, 所以比那题要多一个叶子节点的判断.

Java:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if (root == null)
            return 0;
            
        if (root.left == null && root.right == null)
            return 1;
        else if (root.left == null)
            return this.minDepth(root.right) + 1;
        else if (root.right == null)
            return this.minDepth(root.left) + 1;
        
        int dl = this.minDepth(root.left);
        int dr = this.minDepth(root.right);
        
        return (dl < dr ? dl : dr) + 1;
    }
}

C++:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode *root) {
        if (root == NULL)
            return 0;
        else if (root->left == NULL && root->right == NULL)
            return 1;
        else if (root->left == NULL)
            return minDepth(root->right) + 1;
        else if (root->right == NULL)
            return minDepth(root->left) + 1;
        
        int dl = minDepth(root->left);
        int dr = minDepth(root->right);
        
        return (dl < dr ? dl : dr) + 1;
    }
};

Python:

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return an integer
    def minDepth(self, root):
        if root == None:
            return 0
        elif (root.left == None and root.right == None):
            return 1
        elif root.left == None:
            return self.minDepth(root.right) + 1
        elif root.right == None:
            return self.minDepth(root.left) + 1
        
        dl = self.minDepth(root.left)
        dr = self.minDepth(root.right)
        
        return (dl < dr and dl or dr) + 1
继续查看有关 日志连载的文章

0个访客评论