标签:tac style null ini not val des with else
1 """ 2 Given a binary tree, find its maximum depth. 3 The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 Note: A leaf is a node with no children. 5 Example: 6 Given binary tree [3,9,20,null,null,15,7], 7 3 8 / 9 9 20 10 / 11 15 7 12 return its depth = 3. 13 """ 14 """ 15 此题好题,将提供三种解法 16 """ 17 class TreeNode: 18 def __init__(self, x): 19 self.val = x 20 self.left = None 21 self.right = None 22 23 class Solution1(object): 24 def maxDepth(self, root): 25 if root == None: 26 return 0 27 else: 28 leftdepth = self.maxDepth(root.left) 29 rightdepth = self.maxDepth(root.right) 30 return max(leftdepth, rightdepth)+1 31 """ 32 递归的方法,分别递归左子树,右子树的深度,取最大的+1(根结点) 33 """ 34 class Solution2(object): 35 def maxDepth(self, root): 36 if root == None: 37 return 0 38 queue = [] 39 depth = 0 40 queue.append(root) 41 while queue: 42 cur = [x.val if x else None for x in queue] 43 newqueue = [] 44 for x in queue: 45 if x.left: 46 newqueue.append(x.left) #bug 不是queue,应该是newqueue 47 if x.right: 48 newqueue.append(x.right) 49 queue = newqueue 50 depth += 1 51 return depth 52 53 """用队列进行BFS搜索,记录depth""" 54 55 class Solution3(object): 56 def maxDepth(self, root): 57 if root == None: 58 return 0 59 stack = [] 60 depth = 0 61 stack.append((1, root)) #!!!用一个tuple存当前结点与其深度 62 while stack: 63 current_depth, root = stack.pop() #cur 记录当前结点深度 64 if root: 65 stack.append((current_depth+1, root.left)) #bug (,) 少加了一个括号 66 stack.append((current_depth+1, root.right)) 67 depth = max(depth, current_depth) 68 return depth 69 70 """ 71 用栈进行DFS搜索, 72 值得注意的是:用(current_depth, root)入栈 73 记录当前结点的深度,每入栈一个结点 cur+1 74 """
leetcode104 Maximum Depth of Binary Tree
标签:tac style null ini not val des with else
原文地址:https://www.cnblogs.com/yawenw/p/12254003.html