LeetCode--Maximum Depth of Binary Tree (检索二叉树的最大深度)Python
2017-12-05 13:23
525 查看
题目:
给定一个二叉树,返回这个二叉树的最大深度
解题思路:
使用递归,保存所有叶子节点的深度。选择这些深度中的最大值,则为该二叉树的最大深度。
代码(Python):
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
List = []
if root==None:
return 0
def readTree(root,count):
if root.left==None and root.right==None:
count = count+1
List.append(count)
return
elif root.left==None and root.right!=None:
count = count+1
readTree(root.right,count)
elif root.left!=None and root.right==None:
count = count+1
readTree(root.left,count)
else:
readTree(root.left,count+1)
readTree(root.right,count+1)
readTree(root,0)
print List
return max(List)
给定一个二叉树,返回这个二叉树的最大深度
解题思路:
使用递归,保存所有叶子节点的深度。选择这些深度中的最大值,则为该二叉树的最大深度。
代码(Python):
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
List = []
if root==None:
return 0
def readTree(root,count):
if root.left==None and root.right==None:
count = count+1
List.append(count)
return
elif root.left==None and root.right!=None:
count = count+1
readTree(root.right,count)
elif root.left!=None and root.right==None:
count = count+1
readTree(root.left,count)
else:
readTree(root.left,count+1)
readTree(root.right,count+1)
readTree(root,0)
print List
return max(List)
相关文章推荐
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | 深度优先与广度优先深入理解
- 【LeetCode-面试算法经典-Java实现】【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 二叉树的最大深度 - Easy
- 【LeetCode笔记】Maximum Depth of Binary Tree 二叉树最大深度 递归&非递归
- Leetcode 104 Maximum Depth of Binary Tree 二叉树的最大深度
- 【LeetCode】Maximum Depth of Binary Tree (二叉树最大深度)
- [LeetCode] Maximum Depth of Binary Tree 二叉树的最大深度
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- [leetcode]Maximum Depth of Binary Tree (求二叉树的最大深度 C语言)
- LeetCode----Maximum Depth of Binary Tree 求二叉树最大深度
- Leetcode Maximum Depth of Binary Tree 二叉树最大深度
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- [Leetcode] Maximum depth of binary tree二叉树的最大深度
- 【LeetCode】 Maximum Depth of Binary Tree 二叉树的最大深度
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- LeetCode | Maximum Depth of Binary Tree(二叉树的深度)
- 【二叉树的递归】02二叉树的最大深度【Maximum Depth of Binary Tree】