104.[LeetCode]Maximum Depth of Binary Tree

题意:

求一个二叉树的最大深度

递归:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        else {
            int l = maxDepth(root->left);
            int r = maxDepth(root->right);
            //这里一定要先int,在使用:?进行计算,不然会报错
            return l > r ? l+1 : r+1;
        }
    }
};

问题:

为什么这样写不行?

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        else  return maxDepth(root->left) > maxDepth(root->right) ? maxDepth(root->left)+1 : maxDepth(root->right)+1;

    }
};

这里多执行了 两遍遍历,所以会导致超时间

你可能感兴趣的:(LeetCode)