1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
| class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def __str__(self): return str(self.val)
class BinaryTree():
def Insert(self, root, item): node = TreeNode(item) if root == None: root = node else: queue = [] queue.append(root) while True: pop_node = queue.pop(0) if pop_node.left == None: pop_node.left = node return elif pop_node.right == None: pop_node.right = node return else: queue.append(pop_node.left) queue.append(pop_node.right) return root
def Create(self, items): if len(items) == 0: return TreeNode(0) nodeQueue = [] root = TreeNode(items[0]) nodeQueue.append(root) cur = None lineNodeNum = 2 startIndex = 1 restLength = len(items) - 1 while restLength > 0: i = startIndex while i < startIndex + lineNodeNum: if i == len(items): return root cur = nodeQueue.pop(0) if items[i] != None: cur.left = TreeNode(items[i]) nodeQueue.append(cur.left)
if i + 1 == len(items): return root if items[i + 1] != None: cur.right = TreeNode(items[i + 1]) nodeQueue.append(cur.right) i += 2 startIndex += lineNodeNum restLength -= lineNodeNum lineNodeNum = len(nodeQueue) * 2 return root
def FindParent(self, root, item): if root.val == item: return None queue = [root] while len(queue): pop_node = queue.pop(0) if pop_node.left and pop_node.left.val == item: return pop_node if pop_node.right and pop_node.right.val == item: return pop_node if pop_node.left != None: queue.append(pop_node.left) if pop_node.right != None: queue.append(pop_node.right)
return None
def Delete(self, root, item): ''' 从一颗二叉树中删除一个元素的思路: 先获取 待删除节点 item 的父节点 如果父节点不为空, 判断 item 的左右子树 如果左子树为空且右子树非空,那么判断 item 是父节点的左孩子还是右孩子。如果是左孩子,将父节点的左指针指向 item 的右子树,反之将父节点的右指针指向 item 的右子树 如果右子树为空且左子树非空,同样判断 item 是父节点的左孩子还是右孩子,如果是左孩子,将父节点的左指针指向 item 的左子树,反之将父节点的右指针指向 item 的左子树 如果左右子树均不为空,寻找右子树中的最左叶子节点 x ,将 x 替代要删除的节点。 删除成功,返回 True 删除失败, 返回 False ''' if root == None: return False parent = self.FindParent(root, item) if parent: del_node = parent.left if parent.left.val == item else parent.right
if del_node.left == None and del_node.right == None: del del_node if parent.left.val == item: parent.left = None else: parent.right = None return True
elif del_node.left == None and del_node.right != None: if parent.left.val == item: parent.left = del_node.right else: parent.right = del_node.right del del_node return True
elif del_node.left != None and del_node.right == None: if parent.left.val == item: parent.left = del_node.left else: parent.right = del_node.left del del_node return True
else: tmp_pre = del_node tmp_next = del_node.right if tmp_next.left == None: tmp_pre.right = tmp_next.right tmp_next.left = del_node.left tmp_next.right = del_node.right else: while tmp_next.left: tmp_pre = tmp_next tmp_next = tmp_next.left tmp_pre.left = tmp_next.right tmp_next.left = del_node.left tmp_next.right = del_node.right if parent.left.val == item: parent.left = tmp_next else: parent.right = tmp_next del del_node return True
else: return False
def PreOrder(self, root): """ Pre-Order Traversal of binary tree :param root: root node of target binary tree :return: TreeNode """ if not root: return [None] res = [root.val] left_tree = self.PreOrder(root.left) right_tree = self.PreOrder(root.right) return res + left_tree + right_tree
def PreOrder_circulation(self, root): """ Pre-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ res = [] stack = [] if root: stack.append(root) while len(stack): node = stack.pop() if node == None: res.append(None) else: res.append(node.val) stack.append(node.right) stack.append(node.left) return res
def InOder(self, root): """ In-Order Traversal of binary tree :param root: root node of target binary tree :return: TreeNode """ if not root: return [None] res = [root.val] left_tree = self.InOder(root.left) right_tree = self.InOder(root.right) return left_tree + res + right_tree
def InOder_circulation(self, root): """ In-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ if root == None: return [None] res = [] stack = [root] node = root while len(stack) > 0: if node == None: res.append(None) else: while node: node = node.left stack.append(node) if len(stack): node = stack.pop() if node == None: res.append(None) node = stack.pop() res.append(node.val) node = node.right stack.append(node) return res
def PostOder(self, root): """ Post-Order Traversal of binary tree :param root: root node of target binary tree :return: TreeNode """ if not root: return [None] res = [root.val] left_tree = self.PostOder(root.left) right_tree = self.PostOder(root.right) return left_tree + right_tree + res
def PostOder_circulation(self, root): """ Post-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ res = [] stack = [root] pre_Node = None while len(stack) > 0: node = stack.pop() if node == None: res.append(None) else: while node: stack.append(node) node = node.left if len(stack) > 0: temp = stack[-1].right if temp == None or temp == pre_Node: node = stack.pop() res.append(node.val) pre_Node = node node = None else: node = temp return res
def DepthOrder(self, root): """ Depth-first-Order Traversal of binary tree based on recursion :param root: root node of target binary tree :return: TreeNode """ def _dfs(root): if root == None: res.append(None) else: res.append(root.val) _dfs(root.left) _dfs(root.right) res = [] _dfs(root) return res
def DepthOrder_circulation(self, root): """ Depth-first-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ stack = [] res = [] stack.append(root) while len(stack): t = stack.pop() if t == None: res.append(None) else: stack.append(t.right) stack.append(t.left) res.append(t.val) return res
def BreadthOrder(self, root): """ Breadth-first-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ queue = [] res = [] queue = [] queue.append(root) while len(queue): t = queue.pop(0) if t == None: res.append(None) else: queue.append(t.left) queue.append(t.right) res.append(t.val) return res
def BinaryTree_main(): _list = [3, 1, None, None, 2]
print("*"*50) print("输入list:{}".format(_list))
print("*"*50) print("创建二叉树") BTree = BinaryTree() root = BTree.Create(_list)
print("*"*50) res = BTree.PreOrder(root) print("前序遍历结果(递归实现):{}".format(res)) res = BTree.PreOrder_circulation(root) print("前序遍历结果(循环实现):{}".format(res))
print("*"*50) res = BTree.InOder(root) print("中序遍历结果(递归实现):{}".format(res))
print("*"*50) res = BTree.PostOder(root) print("后序遍历结果(递归实现):{}".format(res))
print("*"*50) print("层次遍历分为:深度优先遍历和广度优先遍历两种。")
print("*"*50) res = BTree.DepthOrder(root) print("层次遍历:深度优先遍历(递归实现) {}".format(res)) res = BTree.DepthOrder_circulation(root) print("层次遍历:深度优先遍历(循环实现) {}".format(res))
print("*"*50) res = BTree.BreadthOrder(root) print("层次遍历:广度优先遍历(循环实现) {}".format(res))
print("*"*50) insert_val = 6 print("插入{}到二叉树".format(insert_val)) BTree.Insert(root, insert_val) res = BTree.BreadthOrder(root) print("完成插入后的二叉树(广度优先遍历)") print(res)
print("*"*50) delete_val = 1 print("删除节点:{}".format(delete_val)) result = BTree.Delete(root, delete_val) print("{}".format("删除成功" if result else "删除失败")) res = BTree.BreadthOrder(root) print("完成删除后的二叉树(广度优先遍历)") print(res)
class BinarySearchTree:
def Insert(self, root, x): """ Insert TreeNode in binary tree :param root: root node of target binary tree x: TreeNode which wait for to be inserted :return: TreeNode """ if root == None: root = TreeNode(x) else: if x < root.val: root.left = self.Insert(root.left, x) else: root.right = self.Insert(root.right, x) return root
def CreateBT(self, items): """ Create a binary tree based on a list :param items: list made of items :return: TreeNode """ root = None for item in items: root = self.Insert(root, item) return root
def FindMin(self, root): """ Find minimum element in binary tree :param root: root node of target binary tree :return: TreeNode """ if root: while root.left: root = root.left return root
def Delete(self, root, x): """ Delete TreeNode in binary tree :param root: root node of target binary tree :return: TreeNode """ if root: if x < root.val: root.left = self.Delete(root.left, x) elif x > root.val: root.right = self.Delete(root.right, x) elif root.left and root.right: tmp = self.FindMin(root.right) min_val = tmp.val root.right = self.Delete(root.right, min_val) else: root = root.right if root.left is None else root.left return root
def PreOrder(self, root): """ Pre-Order Traversal of binary tree :param root: root node of target binary tree :return: TreeNode """ if not root: return [] res = [root.val] left_tree = self.PreOrder(root.left) right_tree = self.PreOrder(root.right) return res + left_tree + right_tree
def PreOrder_circulation(self, root): """ Pre-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ res = [] stack = [] if root: stack.append(root) while len(stack): node = stack.pop() if node == None: continue res.append(node.val) stack.append(node.right) stack.append(node.left) return res
def InOder(self, root): """ In-Order Traversal of binary tree :param root: root node of target binary tree :return: TreeNode """ if not root: return [] res = [root.val] left_tree = self.InOder(root.left) right_tree = self.InOder(root.right) return left_tree + res + right_tree
def InOder_circulation(self, root): """ In-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ res = [] stack = [] node = root while node or len(stack) > 0: while node: stack.append(node) node = node.left if len(stack): node = stack.pop() res.append(node.val) node = node.right return res
def PostOder(self, root): """ Post-Order Traversal of binary tree :param root: root node of target binary tree :return: TreeNode """ if not root: return [] res = [root.val] left_tree = self.PostOder(root.left) right_tree = self.PostOder(root.right) return left_tree + right_tree + res
def PostOder_circulation(self, root): """ Post-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ res = [] stack = [] node = root pre_Node = None while node or len(stack) > 0: while node: stack.append(node) node = node.left if len(stack) > 0: temp = stack[-1].right if temp == None or temp == pre_Node: node = stack.pop() res.append(node.val) pre_Node = node node = None else: node = temp return res
def DepthOrder(self, root): """ Depth-first-Order Traversal of binary tree based on recursion :param root: root node of target binary tree :return: TreeNode """ def _dfs(root): if root != None: res.append(root.val) _dfs(root.left) _dfs(root.right) res = [] _dfs(root) return res
def DepthOrder_circulation(self, root): """ Depth-first-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ stack = [] res = [] if root.val == None: return res stack.append(root) while len(stack): t = stack.pop() if t == None: continue stack.append(t.right) stack.append(t.left) res.append(t.val) return res
def BreadthOrder(self, root): """ Breadth-first-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ queue = [] res = [] queue = [] queue.append(root) while len(queue): t = queue.pop(0) if t == None: continue queue.append(t.left) queue.append(t.right) res.append(t.val) return res
def BinarySearchTree_main(): BSTree = BinarySearchTree() root = None _list = [6, 2, 8, 1, 5, 3, 4]
print("*"*50) print("输入列表:{}".format(_list)) root = BSTree.CreateBT(_list)
print("*"*50) print("所谓前序、中序、后序,是指根节点的位置在输出序列的前面、中间、后面,而左节点永远在右节点的前面。")
print("*"*50) res = BSTree.PreOrder(root) print("前序遍历结果(递归实现):{}".format(res)) res = BSTree.PreOrder_circulation(root) print("前序遍历结果(循环实现):{}".format(res))
print("*"*50) res = BSTree.InOder(root) print("中序遍历结果(递归实现):{}".format(res)) res = BSTree.InOder_circulation(root) print("中序遍历结果(循环实现):{}".format(res))
print("*"*50) res = BSTree.PostOder(root) print("后序遍历结果(递归实现):{}".format(res)) res = BSTree.PostOder_circulation(root) print("后序遍历结果(循环实现):{}".format(res))
print("*"*50) print("层次遍历分为:深度优先遍历和广度优先遍历两种。")
print("*"*50) res = BSTree.DepthOrder(root) print("层次遍历:深度优先遍历(递归实现) {}".format(res)) res = BSTree.DepthOrder_circulation(root) print("层次遍历:深度优先遍历(循环实现) {}".format(res))
print("*"*50) res = BSTree.BreadthOrder(root) print("层次遍历:广度优先遍历(循环实现) {}".format(res))
print("*"*50) mini_node = BSTree.FindMin(root) print("寻找最小节点:{}".format(mini_node.val))
print("*"*50) delet_node = 1 res = BSTree.InOder(root) print("删除节点{}前的中序遍历,{}".format(delet_node, res)) BSTree.Delete(root, delet_node) res = BSTree.InOder(root) print("删除节点{}后的中序遍历,{}".format(delet_node, res))
if __name__ == "__main__": print("测试普通二叉树") BinaryTree_main() print("-"*50) print("测试二叉搜索树") BinarySearchTree_main()
|