码疯窝

LeetCode 每日一题 — Maximum Depth of Binary Tree

2014/12/10 10:06:28    分类: 日志连载    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.

算法分析: 这道题目很简单, 就是考一个递归, 时间复杂度: O(n), 空间复杂度 O(n)

Java:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    public int maxDepth(TreeNode root) {
        if (root == null)
            return 0;
        
        int dl = this.maxDepth(root.left);
        int dr = this.maxDepth(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 maxDepth(TreeNode *root) {
        if (root == NULL)
            return 0;
        
        int dl = maxDepth(root->left);
        int dr = maxDepth(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 maxDepth(self, root):
        if (root == None):
            return 0
        
        dl = self.maxDepth(root.left)
        dr = self.maxDepth(root.right)
        
        return (dl > dr and dl or dr) + 1
继续查看有关 日志连载的文章

0个访客评论