Leetcode 树 Maximum Depth of Binary Tree

时间:2014-05-11 01:58:31   收藏:0   阅读:441

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Maximum Depth of Binary Tree

 Total Accepted: 16605 Total Submissions: 38287

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.




题意:求给定的一棵二叉树的最大深度

思路:dfs递归。树的最大深度=max(左子树的最大深度,右子树的最大深度) + 1

复杂度:时间O(n)(因为每个节点都要访问一次),空间O(log n)(因为递归压栈要保存root指针,栈最大为log n)

相关题目: Minimum Depth of Binary Tree

/**
 * 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;
        return max(maxDepth(root->left) , maxDepth(root->right))  + 1;
    }
   
};



Leetcode 树 Maximum Depth of Binary Tree,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!