To prove safety offer-- tree

Description Title
input result and the preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free. Before entering e.g. preorder traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6} order traversal sequence, and the reconstructed binary tree return.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if not pre:
            return None
        elif len(pre) == 1:
            return TreeNode(pre[0])
        else:
            root = TreeNode(pre[0])
            root.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1], tin[:tin.index(pre[0])])
            root.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:], tin[tin.index(pre[0])+1:])
        return root

Title Description
Given a binary tree and a node which is, find the next node in a preorder traversal order and returns. Note that the node in the tree contains not only the left and right child nodes, the parent node contains a pointer pointing to.

# -*- coding:utf-8 -*-
# class TreeLinkNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None
class Solution:
    def GetNext(self, pNode):
        # write code here
        if not pNode:
            return None
        if pNode.right:
            pNode = pNode.right
            while pNode.left:
                pNode = pNode.left
            return pNode
        while pNode.next:
            p = pNode.next
            if pNode == p.left:
                return p
            pNode = p
        return None

Title Description
Please implement a function, a binary tree is used to determine not symmetrical. Note that if a binary image is a binary tree with this same definition as symmetrical.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        if not pRoot:
            return True
        return self.comTree(pRoot.left, pRoot.right)
    
    def comTree(self, left, right):
        if not left and not right:
            return True
        if not left or not right:
            return False
        if left.val == right.val:
            return self.comTree(left.left, right.right) and self.comTree(left.right, right.left)
        else:
            return False

Title Description
Please implement a function according to a binary tree zigzag print, i.e., the first row from left to right order of printing, the print order of the second layer is from right to left, the third row from left to right order of printing, other line and so on.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        res = []
        stack = [pRoot]
        left_right = False
        while stack:
            tmp = []
            tmpres = []
            for i in stack:
                tmpres.append(i.val)
                if i.left:
                    tmp.append(i.left)
                if i.right:
                    tmp.append(i.right)
            if left_right:
                tmpres = tmpres[::-1]
            if tmpres:
                res.append(tmpres)
            left_right = not left_right
            stack = tmp
        return res

Title Description
top to bottom, binary print layer, the same layer as the output node from left to right. Each line of output layer.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表[[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        res = []
        current = [pRoot]
        while current:
            tmp = []
            restmp = []
            for i in current:
                restmp.append(i.val)
                if i.left:
                    tmp.append(i.left)
                if i.right:
                    tmp.append(i.right)
            current = tmp
            res.append(restmp)
        return res

Title Description
Please implement two functions are used to serialize and deserialize binary

It refers to a sequence of binary: the binary tree is saved in a format string in accordance with the result of a traversing manner such that the memory can be set up binary persisted. Serialization may be based on the first order, in sequence, after, the binary tree traversal sequence is modified, the sequence of the result is a string representing the blank nodes (#) by some sequences of symbol to! End node represents a value (value!).

Deserialized binary tree means: The serialized string str some results obtained traversal order to reconstruct a binary tree.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import re
class Solution:
    
    def __init__(self):
        self.flag = -1
    
    def Serialize(self, root):
        # write code here
        if not root:
            return '#'
        return str(root.val) +'!'+ self.Serialize(root.left) + '!' + self.Serialize(root.right)
    
    def Deserialize(self, s):
        # write code here
        self.flag += 1
        L = re.split(',|!', s)
        
        if self.flag > len(L):
            return None
        root = None
        
        while L[self.flag] != '#':
            root = TreeNode(int(L[self.flag]))
            root.left = self.Deserialize(s)
            root.right = self.Deserialize(s)
        return root

Description Title
given a binary search tree, find the k-th smaller nodes therein. For example, (5,3,7,2,4,6,8), the numerical values according to the third junction point is 4 summary.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回对应节点TreeNode
    def KthNode(self, pRoot, k):
        # write code here
        if k < 0:
            return None
        count = 0
        tmp = []
        while tmp or pRoot:
            if pRoot:
                tmp.append(pRoot)
                pRoot = pRoot.left
            else:
                pRoot = tmp.pop()
                count += 1
                if count == k:
                    return pRoot
                pRoot = pRoot.right
        return None

Title describes
how to get the median of a data stream? If the numerical value is read from the odd data stream, then the median value is located in the middle of all values after sorting. If an even number value is read out from the data stream, then the median is the average of two numbers after all intermediate values of order. We use the Insert () method to read the data stream, using GetMedian () method to get the current median data is read.

# -*- coding:utf-8 -*-
import heapq
class Solution:

    def __init__(self):
        self.count = 0
        self.minheap = []
        self.maxheap = []

    def Insert(self, num):
        # write code here
        self.count += 1
        if self.count&1 :
            heapq.heappush(self.minheap, num)
            min_heap_top = heapq.heappop(self.minheap)
            heapq.heappush(self.maxheap, -min_heap_top)
        else:
            heapq.heappush(self.maxheap, -num)
            max_heap_top = heapq.heappop(self.maxheap)
            heapq.heappush(self.minheap, -max_heap_top)
            
    def GetMedian(self, s):
        # write code here
        if self.count&1:
            return -self.maxheap[0]
        else:
            return (self.minheap[0] - self.maxheap[0])/2.0
Released nine original articles · won praise 0 · Views 754

Guess you like

Origin blog.csdn.net/weixin_42707571/article/details/105257066