def buildTreeFromPreIn(self,preorder,pB,pE,inorder,iB,iE): if pB > pE or iB > iE: return None if pB == pE: return TreeNode(preorder[pE]) root = TreeNode(preorder[pB]) mid = 0 for i in range(iB,iE+1): if inorder[i] == preorder[pB]: mid = i break leftSize = mid-iB root.left = self.buildTreeFromPreIn(preorder,pB+1,pB+leftSize,inorder,iB,mid-1) root.right = self.buildTreeFromPreIn(preorder,pB+leftSize+1,pE,inorder,mid+1,iE) return root
def connect(self, root): """ 这里给的图确定是一个完全二叉树,但是不是满二叉树。 :type root: TreeLinkNode :rtype: nothing """ if not root: return tempRoot = root nextLineRoot = tempRoot while tempRoot: nextLineRoot = None nextLineRootFound = False guard = TreeNode(-1) # 找到当前行的第一个儿子节点 nextLineRoot while tempRoot: if tempRoot.left: if not nextLineRootFound: nextLineRoot = tempRoot.left nextLineRootFound = True guard.next = tempRoot.left guard = guard.next if tempRoot.right: if not nextLineRootFound: nextLineRoot = tempRoot.right nextLineRootFound = True guard.next = tempRoot.right guard = guard.next tempRoot = tempRoot.next if not nextLineRoot: return tempRoot = nextLineRoot
def dfs(self, begin, end): """ 从begin到end,生成BST :param begin:int :param end: int :return: List[TreeNode] """ ans = [] if begin > end: ans.append(None) return ans if begin == end: t = TreeNode(begin) ans.append(t) return ans if begin + 1 == end: t1 = TreeNode(begin) t1.right = TreeNode(end) ans.append(t1) t2 = TreeNode(end) t2.left = TreeNode(begin) ans.append(t2) return ans for i in range(begin, end + 1): leftTreeSet = self.dfs(begin, i - 1) rightTreeSet = self.dfs(i + 1, end) for nodeL in leftTreeSet: for nodeR in rightTreeSet: ro = TreeNode(i) ro.left = nodeL ro.right = nodeR ans.append(ro) return ans
def buildTreeFromInPost(self, inorder, iB, iE, postorder, pB, pE): """ 根据中根和后根遍历构建二叉树。后跟遍历的最后一个是根。 :param inorder: List[int] :param iB:int :param iE:int :param postorder: List[int] :param pB: int :param pE:int :return:TreeNode """ if iB > iE or pB > pE: return None if iB == iE: return TreeNode(inorder[iE]) root = TreeNode(postorder[pE]) mid = inorder.index(postorder[pE]) leftLen = mid - iB root.left = self.buildTreeFromInPost(inorder, iB, mid - 1, postorder, pB, pB + leftLen - 1) root.right = self.buildTreeFromInPost(inorder, mid + 1, iE, postorder, pB + leftLen, pE - 1) return root
def buildBST(self,begin,end): """ 按照中根遍历的顺序构建BST :param head: ListNode :param begin: int :param end: int :return: TreeNode """ if begin > end: return None mid = (begin+end)//2 leftTree = self.buildBST(begin,mid-1) root = TreeNode(self.node.val) root.left = leftTree self.node = self.node.next root.right = self.buildBST(mid+1,end) return root