二叉树的层级遍历转换
定义二叉树
class TreeNode(): def __init__(self, val = None, left = None, right = None): self.left = left self.right = right self.val = val
1. 根据提供的列表创建成对应的二叉树,-1代表节点为空
例如:
输入:[3,9,20,-1,-1,15,7,-1,-1,-1,-1]
输出:
3
/ \
9 20
/ \
15 7
#创建二叉树 class Solution: def createtree(self, nums): if not nums: return None new_tree = TreeNode(nums.pop(0)) tree, left = new_tree, True stack = [tree] while stack: node = stack.pop(0) while nums: pop_num = nums.pop(0) if left: if pop_num != -1: node.left = TreeNode(pop_num) stack.append(node.left) left = False else: if pop_num != -1: node.right = TreeNode(pop_num) stack.append(node.right) left = True if left: break return new_tree tree = Solution().createtree([3,9,20,-1,-1,15,7,-1,-1,-1,-1])
2. 根据二叉树层次遍历
例如:
输入:
3
/ \
9 20
/ \
15 7
输出:[3,9,20,-1,-1,15,7,-1,-1,-1,-1]
#层级遍历 class Solution: def leveltravel(self, tree): if not tree: return [] results = [tree.val] stack = [tree] while stack: node = stack.pop(0) if node.left: results.append(node.left.val) stack.append(node.left) else: results.append(-1) if node.right: results.append(node.right.val) stack.append(node.right) else: results.append(-1) return results # tree = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7))) res = Solution().leveltravel(tree) print(res)