LCP104 LeetCode 104. Maximum Depth of Binary Tree

来源:互联网 发布:c语言编写的交易程序 编辑:程序博客网 时间:2024/04/28 19:41

前言

有一种代码的美简直让人拍案叫绝!
这道题目曾在阿里的电话面试中被问到过,当时想了大半天才憋出个蹩脚的解法,被指责算法水平太差。
今天看到这个题目,做了半天,还用了一个类下的全局变量。几次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);

最后再说两句

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

0 0
原创粉丝点击