标签:i+1 result dep set 返回 最大 python nod 打印二叉树
定义二叉树:
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None
构建二叉树:
# 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): if not pre or not tin: return None root = TreeNode(pre[0])#根节点 # 判断输入的两个序列是不是匹配 if set(pre) != set(tin): return None i = tin.index(root.val) # i == 3 root.left = self.reConstructBinaryTree(pre[1:i+1],tin[:i]) # 列表:左闭右开 root.right = self.reConstructBinaryTree(pre[i+1:],tin[i+1:]) return root
BFS:
def BFS(self, root): # 宽度优先遍历BFS array = [] result = [] if root == None: return result array.append(root) while array: newNode = array.pop(0) # 根结点 result.append(newNode.val) if newNode.left != None: array.append(newNode.left) if newNode.right != None: array.append(newNode.right) return result
先序遍历:
1.递归版本:
def pre_traversal(self): ret = [] def traversal(head): if not head: return ret.append(head.val) traversal(head.left) traversal(head.right) traversal(self.root) return ret
2.非递归版本
# 先序打印二叉树(非递归) def preOrderTravese(node): stack = [node] while len(stack) > 0: print(node.val) if node.right is not None: stack.append(node.right) if node.left is not None: stack.append(node.left) node = stack.pop()
中序遍历:
1.递归版本
def in_traversal(self): ret = [] def traversal(head): if not head: return traversal(head.left) ret.append(head.val) traversal(head.right) traversal(self.root) return ret
2.非递归版本
# 中序打印二叉树(非递归) def inOrderTraverse(node): stack = [] pos = node while pos is not None or len(stack) > 0: if pos is not None: stack.append(pos) pos = pos.left else: pos = stack.pop() print(pos.val) pos = pos.right
后序遍历:
1.递归版本
def post_traversal(self): ret = [] def traversal(head): if not head: return traversal(head.left) traversal(head.right) ret.append(head.val) traversal(self.root) return ret
2.非递归版本
# 后序打印二叉树(非递归) # 使用两个栈结构 # 第一个栈进栈顺序:左节点->右节点->跟节点 # 第一个栈弹出顺序: 跟节点->右节点->左节点(先序遍历栈弹出顺序:跟->左->右) # 第二个栈存储为第一个栈的每个弹出依次进栈 # 最后第二个栈依次出栈 def postOrderTraverse(node): stack = [node] stack2 = [] while len(stack) > 0: node = stack.pop() stack2.append(node) if node.left is not None: stack.append(node.left) if node.right is not None: stack.append(node.right) while len(stack2) > 0: print(stack2.pop().val)
求二叉树最大深度:
# 二叉树的最大深度 def bTreeDepth(node): if node is None: return 0 ldepth = bTreeDepth(node.left) rdepth = bTreeDepth(node.right) return (max(ldepth, rdepth) + 1)
求二叉树节点个数:
# 求二叉树节点个数 def treeNodenums(node): if node is None: return 0 nums = treeNodenums(node.left) nums += treeNodenums(node.right) return nums + 1
标签:i+1 result dep set 返回 最大 python nod 打印二叉树
原文地址:https://www.cnblogs.com/DMajor/p/9838040.html