1、重建二叉树
""" 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: #根据中序和前序遍历重建二叉树 def reConstructBinaryTree(self, pre, tin): # write code here if len(pre) == 0: return None if len(pre) == 1: return TreeNode(pre[0]) else: flag = TreeNode(pre[0]) flag.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])]) flag.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:] ) return flag #根据中序和后序遍历重建二叉树 def reConstructBinaryTree2(self, pos, tin): # write code here if len(pos) == 0: return None if len(pos) == 1: return TreeNode(pos[-1]) else: flag = TreeNode(pos[-1]) flag.left = self.reConstructBinaryTree2(pos[:tin.index(pos[-1])],tin[:tin.index(pos[-1])]) flag.right = self.reConstructBinaryTree2(pos[tin.index(pos[-1]):-1],tin[tin.index(pos[-1])+1:] ) return flag
2、二叉树的镜像
""" 操作给定的二叉树,将其变换为源二叉树的镜像。 """ class Solution: # 返回镜像树的根节点 def Mirror(self, root): # write code here if root == None: return None else: root.left,root.right = root.right,root.left self.Mirror(root.left) self.Mirror(root.right) return root
3、从上往下打印二叉树
""" 从上往下打印出二叉树的每个节点,同层节点从左至右打印。 """ class Solution: def PrintFromTopToBottom(self, root): # write code here l=[] if not root: return [] q=[root] while q: t=q.pop(0) l.append(t.val) if t.left: q.append(t.left) if t.right: q.append(t.right) return l
4、把二叉树打印成多行
""" 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。 """ class Solution: # 返回二维列表,一层一行 def Print(self, root): # write code here l=[] if not root: return [] q=[root] while q: row = [] for i in q: row.append(i.val) l.append(row) for i in range(len(q)): node = q.pop(0) if node.left: q.append(node.left) if node.right: q.append(node.right) return l
5、按之字形打印二叉树
""" 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印, 第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。 """ class Solution: # 返回二维列表,一层一行 def Print(self, root): # write code here l=[] if not root: return [] q=[root] while q: row = [] for i in q: row.append(i.val) l.append(row) for i in range(len(q)): node = q.pop(0) if node.left: q.append(node.left) if node.right: q.append(node.right) for i in range(len(l)): if i%2 ==1: l[i]=list(reversed(l[i])) return l
6、二叉树中和为某一值的路径
""" 输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 (注意: 在返回值的list中,数组长度大的数组靠前) """ class Solution: # 返回二维列表,内部每个列表表示找到的路径 def FindPath(self, root, expectNumber): if not root: return [] tmp = [] if not root.left and not root.right and root.val == expectNumber: return [[root.val]] else: left = self.FindPath(root.left,expectNumber-root.val) right = self.FindPath(root.right,expectNumber-root.val) for item in left+right: tmp.append([root.val]+item)#[3]+[4]=[3,4] return tmp
原文:https://www.cnblogs.com/fighting25/p/11285409.html