二叉树转单链表
二叉树转换为单链表,展开后的单链表应该与二叉树先序遍历顺序相同。
1
/ \
2 5
/ \ \
3 4 6
简单方法一:
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
def pre(root):
if root:
list_tree.append(root.val)
pre(root.left)
pre(root.right)
def creatListNode(l):
if l==None:
return None
head = ListNode(l[0])
curr = head
for i in range(1,len(l)):
curr.next = ListNode(l[i])
curr = curr.next
return head
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(6)
list_tree = []
pre(root)
print(list_tree)
ret_ListNode = creatListNode(list_tree)
while ret_ListNode:
print(ret_ListNode.val)
ret_ListNode = ret_ListNode.next
优化方法二、
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def flatten(root: TreeNode) -> ListNode:
if not root:
return None
# 创建单链表的头节点
head = ListNode(root.val)
# 递归处理左子树和右子树
left_list = flatten(root.left)
right_list = flatten(root.right)
# 将左子树链表连接到当前节点后面
head.next = left_list
# 找到左子树链表的最后一个节点,并将右子树链表连接到其后
last = head
while last.next:
last = last.next
last.next = right_list
return head
def flatten_tree_to_list(root: TreeNode) -> ListNode:
return flatten(root)
# 构建示例二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(6)
# 转换为单链表并返回头节点
list_head = flatten_tree_to_list(root)
# 输出单链表的值,以验证结果
result = []
while list_head:
result.append(list_head.val)
list_head = list_head.next
result
中序后序遍历构造二叉树
描述
给定一个二叉树的中序与后序遍历结果,请你根据两个序列构造符合这两个序列的二叉树。
例如输入[2,1,4,3,5],[2,4,5,3,1]时,
根据中序遍历的结果[2,1,4,3,5]和后序遍历的结果[2,4,5,3,1]可构造出二叉树{1,2,3,#,#,4,5},如下图所示:
示例1
输入:
[1],[1]
返回值:
{1}
示例2
输入:
[2,1,4,3,5],[2,4,5,3,1]
返回值:
{1,2,3,#,#,4,5}
思路:
中序遍历: 左 -> 根 -> 又 后序遍历: 左 -> 右 -> 根 则后序遍历的最后一个节点为根节点,该节点在中序数组中的索引 idx 的左侧即为左子树[0:idx],右侧为右子树 [idx + 1:],该索引代表了左子树的长度,在后序数组中左子树为[0:idx],右子树为[idx:-1],从上至下建立树
代码
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param inorder int整型一维数组 中序遍历序列
# @param postorder int整型一维数组 后序遍历序列
# @return TreeNode类
#
class Solution:
def buildTree(self , inorder: List[int], postorder: List[int]) -> TreeNode:
# write code here
if not inorder or not postorder:
return None
root = TreeNode(postorder[-1])
idx = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:idx],postorder[:idx])
root.right = self.buildTree(inorder[idx+1:],postorder[idx:-1])
return root