• 剑指offer python版 重建二叉树


    from collections import deque
    
    
    class TreeNode(object):
        """
        二叉树结点定义
        """
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    
    class Tree(object):
        """
        二叉树
        """
        def __init__(self):
            self.root = None
    
        def bfs(self):
            ret = []
            queue = deque([self.root])
            while queue:
                node = queue.popleft()
                if node:
                    ret.append(node.val)
                    queue.append(node.left)
                    queue.append(node.right)
            return ret
    
        def pre_traversal(self):
            ret = []
    
            def traversal(head):
                if not head:
                    return
                ret.append(head.val)
                traversal(head.left)
                traversal(head.right)
    
            traversal(self.root)
            return ret
    
        def in_traversal(self):
            ret = []
    
            def traversal(head):
                if not head:
                    return
                traversal(head.left)
                ret.append(head.val)
                traversal(head.right)
    
            traversal(self.root)
            return ret
    
        def post_traversal(self):
            ret = []
    
            def traversal(head):
                if not head:
                    return
                traversal(head.left)
                traversal(head.right)
                ret.append(head.val)
    
            traversal(self.root)
            return ret
    
    
    def construct_tree(preorder=None, inorder=None):
        """
        构建二叉树
        """
        if not preorder or not inorder:
            return None
        index = inorder.index(preorder[0])
        left = inorder[0:index]
        right = inorder[index+1:]
        root = TreeNode(preorder[0])
        root.left = construct_tree(preorder[1:1+len(left)], left)
        root.right = construct_tree(preorder[-len(right):], right)
        return root
    
    
    if __name__ == '__main__':
        t = Tree()
        root = construct_tree([1, 2, 4, 7, 3, 5, 6, 8], [4, 7, 2, 1, 5, 3, 8, 6])
        t.root = root
        print t.bfs()
        print t.pre_traversal()
        print t.in_traversal()
    print t.post_traversal()
  • 相关阅读:
    布隆过滤器(Bloom Filter)详解
    css-鼠标经过图片效果
    css-卡牌反转(两个内容)
    wow 属性
    小常识
    裁剪图片
    js电梯导航效果
    banner缓慢缩小过渡效果
    css——鼠标经过按钮时样式
    redis面试题redis的lru算法实现到手写lru算法
  • 原文地址:https://www.cnblogs.com/xzm123/p/9874894.html
Copyright © 2020-2023  润新知