剑指offer python版 二叉树的深度
Posted findtruth123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指offer python版 二叉树的深度相关的知识,希望对你有一定的参考价值。
from collections import deque def get_depth(tree): if not tree: return 0 if not tree.left and not tree.right: return 1 return 1 + max(get_depth(tree.left), get_depth(tree.right)) class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Tree(object): def __init__(self): self.root = None def construct_tree(self, values=None): if not values: return None self.root = TreeNode(values[0]) queue = deque([self.root]) leng = len(values) nums = 1 while nums < leng: node = queue.popleft() if node: node.left = TreeNode(values[nums]) if values[nums] else None queue.append(node.left) if nums + 1 < leng: node.right = TreeNode(values[nums + 1]) if values[nums + 1] else None queue.append(node.right) nums += 1 nums += 1 def bfs(self): ret = [] queue = deque([self.root]) while queue: node = queue.popleft() if node: ret.append(node.val) queue.append(node.left) queue.append(node.right) return ret def bfs(tree): if not tree: return None stack = [tree] ret = [] while stack: node = stack.pop(0) ret.append(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) return ret if __name__ == ‘__main__‘: t = Tree() t.construct_tree([1, 2, 3]) print t.bfs() print get_depth(t.root)
以上是关于剑指offer python版 二叉树的深度的主要内容,如果未能解决你的问题,请参考以下文章