ACM模式下链表、二叉树的输入Python实现

链表

  1. 定义链表结构
  2. 数组2链表
  3. 打印链表验证
# 定义链表结构
class ListNode:
    def __init__(self,val,next=None):
        self.val = val
        self.next = next

# 数组转链表
def nums2ListNode(nums):
    dummy = ListNode(None)
    root = ListNode(nums[0])
    dummy.next = root
    i = 1
    while i < len(nums):
        node = ListNode(nums[i])
        root.next = node
        root = root.next
        i += 1
    root.next = None
    return dummy.next

# 打印链表
res = []
nums = [1,2,3,4,5]
print("数组为:",nums)
root = nums2ListNode(nums)
print("\n链表生成成功")
while root:
    res.append(root.val)
    root = root.next
print("\n打印链表:",res)

输出:

数组为: [1, 2, 3, 4, 5]

链表生成成功

打印链表: [1, 2, 3, 4, 5]

二叉树

主要分成三部分:

  1. 定义二叉树结构TreeNode
  2. 数组转二叉树
  3. 二叉树层序遍历验证
# 定义二叉树类函数
class TreeNode:
    def __init__(self,val=0,left=None,right=None):
        self.val = val
        self.left = left
        self.right = right

# 由数组转二叉树
def construct_binary_tree(nums,index):
    if index >= len(nums):
        return
    # 0作为空节点
    if nums[index]==nullnum:
        return None
    left = index*2+1
    right = index*2+2
    root = TreeNode(nums[index])
    root.left = construct_binary_tree(nums, left)
    root.right = construct_binary_tree(nums, right)
    return root
nums = [1,2,3,0,4,5,0]
nullnum = 0
print("输入数组为:",nums)
print("\n{}代表空节点".format(nullnum))
root = construct_binary_tree(nums,0)
print("\n二叉树已生成\n")
# 中序遍历
def cxbl(root):
    st = [root]
    res = []
    while st:
        l = len(st)
        for i in range(l):
            node = st.pop(0)
            res.append(node.val)
            if node.left:
                st.append(node.left)
            if node.right:
                st.append(node.right)
    return res
print('中序遍历结果:',cxbl(root))

输出:

输入数组为: [1, 2, 3, 0, 4, 5, 0]

0代表空节点

二叉树已生成

中序遍历结果: [1, 2, 3, 4, 5]

你可能感兴趣的:(数据结构及算法,数组转二叉树)