from my_data_structure import generate_treenode, print_treenode tc = [ generate_treenode('8,6,10,5,7,9,11'), # 只有一个节点的二叉树 generate_treenode('1'), # 只有左子树的二叉树 generate_treenode('1,2,null,4'), ] def main(tree): if tree.left == tree.right == None: return tree tree.left, tree.right = tree.right, tree.left if tree.left: main(tree.left) if tree.right: main(tree.right) return tree if __name__ == '__main__': for t in tc: print_treenode(main(t))
from my_data_structure import generate_treenode, print_treenode, TreeNode tc = [ generate_treenode('5,3,6,2,4,null,7'), generate_treenode('1,null,2'), generate_treenode('1,null,2'), generate_treenode('0'), generate_treenode('5,3,6,2,4,null,7'), generate_treenode( '2,0,33,null,1,25,40,null,null,11,31,34,45,10,18,29,32,null,36,43,46,4,null,12,24,26,30,null,null,35,39,42,44,null,48,3,9,null,14,22,null,null,27,null,null,null,null,38,null,41,null,null,null,47,49,null,null,5,null,13,15,21,23,null,28,37,null,null,null,null,null,null,null,null,8,null,null,null,17,19,null,null,null,null,null,null,null,7,null,16,null,null,20,6' ) ] print_treenode(tc[5]) class Solution: def deleteNode(self, root: TreeNode, key: int) -> TreeNode: self.head = root def get_mid_order_next(root: TreeNode, parent: TreeNode): """ 返回一个节点的中序遍历的下一个节点及其父节点。 注意:这里的算法只是这道题适用,因为在题里找中序遍历下一个节点时一定有右子节点,这是所有找中序遍历下一个节点的算法中的一种情况。 """ while root.left: return get_mid_order_next(root.left, root) return root, parent def delete(root, key, parent: TreeNode): # 没找到 if not root: return None
from my_data_structure import generate_treenode, print_treenode, TreeNode tc = [generate_treenode('4,2,7,1,3')] def insertIntoBST(root, val: int): head = root def insert(root, val): if root.val > val: if root.left: insertIntoBST(root.left, val) else: root.left = TreeNode(val) else: if root.right: insertIntoBST(root.right, val) else: root.right = TreeNode(val) insert(root, val) return head if __name__ == '__main__': print_treenode(insertIntoBST(tc[0], 5))
from my_data_structure import generate_treenode, print_treenode tc = [generate_treenode('4,2,7,1,3,5,6')] def searchBST(root, val: int): if not root: return None if root.val == val: return root if root.val > val: return searchBST(root.left, val) else: return searchBST(root.right, val) if __name__ == '__main__': print_treenode(searchBST(tc[0], 7))
node = node.left return node.val else: if not node.parent: # 无父节点 return '最后一位' if node.parent.left and node.parent.left.val == node.val: # 是父节点的左子节点 return node.parent.val else: # 是父节点的右子节点 while node.parent: # 沿右子节点路线一路向上到顶 if node.parent.right.val == node.val: node = node.parent else: break if node.parent: return node.parent.val else: return '最后一位' if __name__ == '__main__': # 打印出当前测试用例的二叉树形状 tc_tree = generate_treenode(tc, True) print_treenode(tc_tree) # 遍历测试每个节点的下一个节点 t, num = 1, 1 # 将num修改为二叉树中节点的个数 while t <= num: tc_node = get_specific_treenode(tc_tree, t) print(tc_node.val, main(tc_node), '\n') t += 1