LCP104 LeetCode 104. Maximum Depth of Binary Tree

前言

有一种代码的美简直让人拍案叫绝!
这道题目曾在阿里的电话面试中被问到过,当时想了大半天才憋出个蹩脚的解法,被指责算法水平太差。
今天看到这个题目,做了半天,还用了一个类下的全局变量。几次WA后终于试到了AC。beats 2.2% Solutions。
看了一个网友的四行C++代码,佩服得五体投地!

题目

Acceptance:48.2% Difficulty: Easy
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.

TagsTreeDepth-first Search

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

题解

分析过程很简单,前序遍历,遍历过程中记录当前的深度,当遍历到叶子节点(leaf node, left == NULL && right == NULL)时,拿当前深度与maxDepth比较,存储较大的到maxDepth。
难度在于弄清楚整个递归过程是怎样的,Depth变量在递归过程中是如何增减的。

蹩脚的代码

class Solution {
public:
    int maxD = 0;
    int compare(int Depth)
    {
        if (Depth > maxD)
            maxD = Depth;
        return 0;
    }
    int preOrderTree(TreeNode* root, int &Depth)
    {
        if (root->left != NULL)
        {
            Depth++;
            preOrderTree(root->left, Depth);
            Depth--;
        }
        if (root->right != NULL)
        {
            Depth++;
            preOrderTree(root->right, Depth);
            Depth--;
        }
        if (root->left == NULL && root->right == NULL)
        {
            compare(Depth);
        }
        return 0;
    }
    int maxDepth(TreeNode* root) 
    {
        if (root == NULL)
            return 0;
        int i = 1;
        preOrderTree(root, i);

        return maxD;
    }
};

令人拍案叫绝的代码

#include <algorithm>

class Solution 
{
public:
    int maxDepth(TreeNode* root) 
    {
        if (root == NULL) 
        {
            return 0;
        }

        return (1 + std::max(maxDepth(root->left), maxDepth(root->right)));
    }
};

其实最后一句不用STL的max也可以搞定。
return (maxDepth(root->left) > maxDepth(root->right)) ? 1 + maxDepth(root->left) : 1 + maxDepth(root->right);

好吧,略啰嗦。
或者

if (maxDepth(root->left) > maxDepth(root->right))
    1 + maxDepth(root->left);
else
    1 + maxDepth(root->right);

最后再说两句

总结自己的不足就在于,递归用的太少了。总是觉得它难就避免使用它,于是就缺乏这个的敏锐度。对递归的理解仍不够透彻。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深海Enoch

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值