码迷,mamicode.com
首页 > 编程语言 > 详细

[数据结构与算法分析(Mark Allen Weiss)]二叉树的插入与删除 @ Python

时间:2014-06-17 14:25:01      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   color   数据   

二叉树的插入与删除,来自Mark Allen Weiss的《数据结构与算法分析》。

# Definition for a  binary tree node
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class BinarySearchTree:
    # @param root, a tree node
    # @return a list of integers
    def Insert(self, root, x):
        if root == None:
            root = TreeNode(x)
        else:
            if x < root.val:
                root.left = self.Insert(root.left, x)
            if x > root.val:
                root.right = self.Insert(root.right, x)
        return root

    def Delete(self, root, x):
        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)
                root.val = tmp.val
                root.right = self.Delete(root.right, root.val)
            elif root.left: root = root.left
            elif root.right: root = root.right
        return root

    def FindMin(self, root):
        if root:
            while root.left:
                root = root.left
        
        return root

    def preorder(self, root):
        if root:
            print root.val
            self.preorder(root.left)
            self.preorder(root.right)

Tree = BinarySearchTree()
root = None
list = [6, 2, 8, 1, 5, 3, 4]
for i in range(len(list)):
    root = Tree.Insert(root, list[i])
Tree.preorder(root)
Tree.Delete(root, 2)
Tree.preorder(root)

 

[数据结构与算法分析(Mark Allen Weiss)]二叉树的插入与删除 @ Python,布布扣,bubuko.com

[数据结构与算法分析(Mark Allen Weiss)]二叉树的插入与删除 @ Python

标签:style   class   blog   code   color   数据   

原文地址:http://www.cnblogs.com/zuoyuan/p/3791801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!