Leetcode No.104 Maximum Depth of Binary Tree 遍历二叉树的深度
来源:互联网 发布:中企网络通信 项目经理 编辑:程序博客网 时间:2024/05/23 22:03
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.
注:题库和图片转自 www.leetcode.com ,所有权归www.leetcode.com仅供交流学习使用,不得用于商业用途
-----------------------------------------------------------------------------------------------------
我的解法:/** * Definition for a binary tree node. * 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 currentDepth = 0; maxDep = 0; if(root != NULL) { travelBinaryTree(root, currentDepth); } return maxDep; }private: int maxDep; void travelBinaryTree(TreeNode* node, int depth) { depth++; maxDep = (depth > maxDep) ? depth : maxDep; if(node->left) travelBinaryTree(node->left, depth); if(node->right) travelBinaryTree(node->right, depth); }};
虽然结果正确,看了一下bbs上的讨论,感觉算法虽然不复杂但是太多代码冗余,leetcode上比较精简的一种解法
class Solution {public: int maxDepth(TreeNode* root) { if (!root) return 0; return 1 + max(maxDepth(root->right), maxDepth(root->left)); }};
利用return的时候累加+1和max宏取最大值来获得最精简的代码。
0 0
- Leetcode No.104 Maximum Depth of Binary Tree 遍历二叉树的深度
- 【LeetCode】Maximum Depth of Binary Tree (二叉树最大深度)
- Leetcode Maximum Depth of Binary Tree 二叉树最大深度
- LeetCode 104 Maximum Depth of Binary Tree(二叉树的最大深度)
- LeetCode-104 Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree--二叉树的深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- maximum-depth-of-binary-tree(二叉树的最大深度)
- 104. Maximum Depth of Binary Tree | 二叉树的深度
- leetcode Maximum Depth of Binary Tree 树的深度
- Maximum Depth of Binary Tree 求二叉树的高度/深度 @LeetCode
- LeetCode | Maximum Depth of Binary Tree(二叉树的深度)
- LeetCode OJ 之 Maximum Depth of Binary Tree (二叉树的最大深度)
- [leetcode]Maximum Depth of Binary Tree (求二叉树的最大深度 C语言)
- leetcode系列(28)Maximum Depth of Binary Tree 求二叉树的最大深度
- Mysql数据库insert into select 单表插入常量
- 翻翻git之---逻辑清晰,简单好用的App内部锁控件 PinLockView
- 强悍的 Ubuntu —— cairo-dock
- Linux(1)Linux常用命令_搜索命令_grep命令
- 【Swift】获取设备信息
- Leetcode No.104 Maximum Depth of Binary Tree 遍历二叉树的深度
- Mac OS X 配置环境变量
- thinkphp连接多数据库
- Linux TCP队列相关参数的总结
- Android layer-list与shape的使用
- 读取Java文件到byte数组的三种方式
- 用几何画板怎么制作三维波纹
- 每日一得--mysql函数与存储过程笔记
- 整体二分<QAQ> && CDQ分治