Maximum Depth of Binary Tree
来源:互联网 发布:手机电玩城刷分币软件 编辑:程序博客网 时间:2024/05/18 01:25
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.
算法解析:既可以用深度优先搜索,也可以用广度优先搜索,前者可以节省代码,后者可以提高速度,但两个方法都不会超时。
C语言版
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */int maxDepth(struct TreeNode* root) { if(root) { root->val = 0; root->val = maxDepth(root->left) + 1; int depth = maxDepth(root->right) + 1; if(root->val < depth) root->val = depth; return root->val; } else return 0;}
Python版(深度优先搜索)
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root: root.val = 0 root.val = self.maxDepth(root.left) + 1 depth = self.maxDepth(root.right) + 1 if root.val < depth: root.val = depth return root.val else: return 0
Python版(更Pythonic的代码,别人写的)
class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
阅读全文
0 0
- 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
- 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
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Haskell语言学习笔记(34)System.Environment
- Vue 2.0 监听文本框内容变化及 ref的使用说明
- JAVA BIO 回顾
- 从kafka中获取数据写入到redis中
- Linux mysql数据库设置区分大小写lower_case_table_names
- Maximum Depth of Binary Tree
- ubuntu下配置python开发环境
- 冒泡排序及C++/java代码实现(BubbleSort)
- 三诺·珊瑚群创新加速器正式启动:新一代生态型创新加速器 中国创业创新
- 行业首款智能手表跟拍与避障无人机XEagle亮相高交会
- 艾瑞数据:解读各家在线音乐应用用户活跃度
- Liferay文件的上传
- 【独家首发】迅雷赚钱宝Pro曝光 外观美型似UFO
- css文本、文字