现在的位置: 首页 > 综合 > 正文

Maximum Depth of Binary Tree

2014年02月25日 ⁄ 综合 ⁄ 共 917字 ⁄ 字号 评论关闭

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.

先贴一个我超时的代码:

/**
 * 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) {
        int depth = 0;
        TreeNode *p = root;
        if(!p) return depth;
        if(maxDepth(p->left)>maxDepth(p->right))
            return depth + maxDepth(p->left);
        else
            return depth + maxDepth(p->right);
        
    }
};

超时原因:

~很显然, maxDepth(p->left)每次求的时候都计算了两次, 这个真是太不明智了

提醒以后,尽量用变量代替繁琐的实现

~超时后不是考虑用非递归方法, 这个当然也可以, 而是考虑递归方法是否是最优的

正确代码:

/**
 * 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) return 0;
        int leftdepth = maxDepth(root->left);
        int rightdepth= maxDepth(root->right);
        if(leftdepth>rightdepth)
            return 1 + leftdepth;
        return 1 + rightdepth;
        
    }
};

抱歉!评论已关闭.