二叉树的输入
1.完全二叉树格式输入
acm模式中一般用输入一行数字代表一个二叉树,一般会以完全二叉树格式输入。这行数字的按照层序遍历的顺序排列,且其中空节点一般会用特定的符号表示,如0或是null可以直接用数组表示二叉树,例如列表Tree, 将Tree[i]的左子树和右子树分别为Tree[2i+1]和Tree[2i+2],不过会比较占用空间。
# 中序遍历
def inorder_traversal(nums, index):
if index >= len(nums) or nums[index] == -1:
return
left, right = 2 * index + 1, 2 * index + 2
inorder_traversal(nums, left)
print(nums[index], end = ' ')
inorder_traversal(nums, right)
# 输入为 1 2 3 null 4 null 5
# 1
# / \
# 2 3
# \ \
# 4 5
if __name__ == "__main__":
nums = input().split()
nums = [int(num) if num != 'null' else -1 for num in nums]
inorder_traversal(nums, 0)
# output: 2 4 1 3 5
也可以用链表实现,更省空间,但操作更复杂一些。
# 定义二叉树类函数
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
# -1作为空节点
if nums[index] == -1:
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
# 中序遍历
def inorder_traversal(root):
if not root:
return
inorder_traversal(root.left)
print(root.val, end=' ')
inorder_traversal(root.right)
# 输入为 1 2 3 null 4 null 5
# 1
# / \
# 2 3
# \ \
# 4 5
if __name__ == "__main__":
nums = input().split()
nums = [int(num) if num != 'null' else -1 for num in nums]
root = construct_binary_tree(nums, 0)
inorder_traversal(root)
# output: 2 4 1 3 5
2.其他格式输入(是不是完全二叉树都可以)(可以统一用这个)
有部分题目的输入格式不是完全二叉树,例如leetcode的二叉树格式,输入的数组虽然也是按照层序遍历的顺序,但并不是每一层的空节点都会表示出来,而是仅表示与非空节点连接的空节点。
# 定义二叉树类函数
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
import collections
# 数组转二叉树
def construct_binary_tree(nums): # ['1', 'null', '1', 'null', '1', '2']
if nums == []:
return
root = TreeNode(nums[0])
queue = collections.deque()
queue.append(root)
i = 1
while i < len(nums):
node = queue.popleft()
if i < len(nums) and nums[i] != -1:
node.left = TreeNode(nums[i])
queue.append(node.left)
i += 1
if i < len(nums) and nums[i] != -1:
node.right = TreeNode(nums[i])
queue.append(node.right)
i += 1
return root
# 中序遍历
def inorder_traversal(root):
if not root:
return
inorder_traversal(root.left)
print(root.val, end=' ')
inorder_traversal(root.right)
# 输入 1 null 1 null 1 2
# 1
# / \
# null 1
# / \
# null 1
# /
# 2
if __name__ == "__main__":
nums = ['1', 'null', '1', 'null', '1', '2']
nums = [int(num) if num != 'null' else -1 for num in nums]
root = construct_binary_tree(nums)
inorder_traversal(root)
# 输出 1 1 2 1
3.构建完全二叉树输入用例(输出带有null)
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: []) -> TreeNode:
if not nums:
return None
# 用于存放构建好的节点
root = TreeNode(-1)
Tree = []
# 将数组元素全部转化为树节点
for i in range(len(nums)):
if nums[i] != -1:
node = TreeNode(nums[i])
else:
node = None
Tree.append(node)
if i == 0:
root = node
# 直接判断2*i+2<len(Tree)会漏掉2*i+1=len(Tree)-1的情况
for i in range(len(Tree)):
if Tree[i] and 2 * i + 1 < len(Tree):
Tree[i].left = Tree[2 * i + 1]
if 2 * i + 2 < len(Tree):
Tree[i].right = Tree[2 * i + 2]
return root
# 算法:中序遍历二叉树
class Solution:
def __init__(self):
self.T = []
def inorder(self, root: TreeNode) -> []:
if not root:
return
self.inorder(root.left)
self.T.append(root.val)
self.inorder(root.right)
return self.T
# 验证创建二叉树的有效性,二叉排序树的中序遍历应为顺序排列
# 输入 1 null 1 null 1 2
# 1
# / \
# null 1
# / \
# null 1
# /
# 2
test_tree = ['1', 'null', '1', 'null', '1', '2']
root = construct_binary_tree(test_tree)
A = Solution()
print(A.inorder(root))
# 输出:['null', 'null', '1', '1', '2', '1']