leetcode(104). Maximum Depth of Binary Tree
来源:互联网 发布:淘宝lolcdk是真的吗 编辑:程序博客网 时间:2024/06/06 00:37
problem
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.
solution
这个是一个比较经典的递归问题,使用递归的方法是最简单的。
# 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 == None: return 0 elif root.left == None and root.right==None: return 1 else: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
这是我第一次提交的代码,后来可以发现可以不用判断左右子树是否是空树,经过优化以后的代码超过了90%的提交。
# 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 == None: return 0 else: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
阅读全文
0 0
- Leetcode 104 Maximum Depth of Binary Tree
- LeetCode(104)Maximum Depth of Binary Tree
- LeetCode 104 Maximum Depth of Binary Tree
- LeetCode: Maximum Depth of Binary Tree [104]
- Leetcode(104)Maximum Depth of Binary Tree
- [leetcode 104] Maximum Depth of Binary Tree
- LeetCode 104 Maximum Depth of Binary Tree
- leetCode #104 Maximum Depth of Binary Tree
- LeetCode 104: Maximum Depth of Binary Tree
- LeetCode 104 Maximum Depth of Binary Tree
- leetcode || 104、Maximum Depth of Binary Tree
- LeetCode 104: Maximum Depth of Binary Tree
- leetcode[104]:Maximum Depth of Binary Tree
- Leetcode[104]-Maximum Depth of Binary Tree
- Leetcode---(104)Maximum Depth of Binary Tree
- leetcode-104-Maximum Depth of Binary Tree
- Leetcode #104 Maximum Depth of Binary Tree
- leetcode 104: Maximum Depth of Binary Tree
- AdaBoost 算法原理及推导
- matlb学习笔记—aAlpha起始点检测
- HDU6031 Innumerable Ancestors 倍增
- python字符编码问题
- 虚拟机安装centos7.2
- leetcode(104). Maximum Depth of Binary Tree
- swift-stroybord和xib关联文件
- Image类跟Sprite类有什么区别?
- 基于YARN的Spark程序工作过程
- 【Java编程教材】Java教程之多线程编程
- tensorflow教程学习二MNIST
- 将已有项目下的html转为haml
- JS的逻辑思维练习
- TensorFlow学习——CIFAR-10(二)代码实现