LCP104 LeetCode 104. Maximum Depth of Binary Tree
2016-06-06 23:54
393 查看
前言
有一种代码的美简直让人拍案叫绝!这道题目曾在阿里的电话面试中被问到过,当时想了大半天才憋出个蹩脚的解法,被指责算法水平太差。
今天看到这个题目,做了半天,还用了一个类下的全局变量。几次WA后终于试到了AC。beats 2.2% Solutions。
看了一个网友的四行C++代码,佩服得五体投地!
题目
Acceptance:48.2% Difficulty: EasyGiven 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.
Tags | Tree | Depth-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);
最后再说两句
总结自己的不足就在于,递归用的太少了。总是觉得它难就避免使用它,于是就缺乏这个的敏锐度。对递归的理解仍不够透彻。。。相关文章推荐
- [javaSE] 多线程通信(等待-唤醒机制)
- C++实验7-最大公约和和最小公倍数
- uva10763 - Foreign Exchange
- 解决【Windows Management Instrumentation(WMI)信息可能损坏】
- BLE开发入门
- 剑指Offer----面试题28----扩展:从1到n中随意取若干数使之与某一数相等
- Codeforces 653A: Tricky Sum(数学)
- socket 错误码
- java 动态性之反射机制 详解 案例
- SQL Server 2016 Enterprise (x64) 中英文下载!
- 激活码
- 洛谷P1141 01迷宫
- jquery.flexslider-min.js实现banner轮播图效果
- 当你要写一个CUDA函数计算后返回多个参数时
- setXfermode属性
- Valid Anagram
- 完成了C++作业,本博客现在开始全面记录acm学习历程,真正的acm之路,现在开始
- Java 高性能I/O设计模式Reactor和Proactor
- [LeedCode]242. Valid Anagram
- 柴俊理金:6、6午夜黄金、宁贵沥青操作策略