From fc33af7d4d18227f6c05d5478f04fc0a7458d215 Mon Sep 17 00:00:00 2001 From: WangSL <48207171+WSL0809@users.noreply.github.com> Date: Mon, 26 Dec 2022 21:15:34 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20list=5Fto=5Ftree(arr)=20?= =?UTF-8?q?=E9=81=BF=E5=85=8D=E5=88=97=E8=A1=A8=E8=B6=8A=E7=95=8C=E7=9A=84?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codes/python/include/binary_tree.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/codes/python/include/binary_tree.py b/codes/python/include/binary_tree.py index de2569e42..c37f7e65a 100644 --- a/codes/python/include/binary_tree.py +++ b/codes/python/include/binary_tree.py @@ -18,24 +18,30 @@ def list_to_tree(arr): """Generate a binary tree with a list Args: - arr ([type]): [description] + arr (list): a list representing a binary tree, where None represents an empty node Returns: - [type]: [description] + TreeNode: the root node of the generated binary tree """ if not arr: return None + if len(arr) < 2: + return TreeNode(arr[0]) i = 1 root = TreeNode(int(arr[0])) queue = collections.deque() queue.append(root) while queue: node = queue.popleft() - if arr[i] != None: + if i >= len(arr): + break + if arr[i] is not None: node.left = TreeNode(int(arr[i])) queue.append(node.left) i += 1 - if arr[i] != None: + if i >= len(arr): + break + if arr[i] is not None: node.right = TreeNode(int(arr[i])) queue.append(node.right) i += 1