mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-01 20:12:07 +08:00
Optimize arrToTree function
in java, cpp, py, go, js, ts.
This commit is contained in:
@ -138,7 +138,7 @@ class BinarySearchTree:
|
||||
""" Driver Code """
|
||||
if __name__ == "__main__":
|
||||
# 初始化二叉搜索树
|
||||
nums = list(range(1, 16))
|
||||
nums = list(range(1, 16)) # [1, 2, ..., 15]
|
||||
bst = BinarySearchTree(nums=nums)
|
||||
print("\n初始化的二叉树为\n")
|
||||
print_tree(bst.root)
|
||||
|
||||
@ -36,5 +36,5 @@ if __name__ == "__main__":
|
||||
print_tree(n1)
|
||||
# 删除结点
|
||||
n1.left = n2
|
||||
print("\n删除结点 P 后\n");
|
||||
print("\n删除结点 P 后\n")
|
||||
print_tree(n1)
|
||||
|
||||
@ -32,7 +32,7 @@ def hier_order(root: TreeNode):
|
||||
if __name__ == "__main__":
|
||||
# 初始化二叉树
|
||||
# 这里借助了一个从数组直接生成二叉树的函数
|
||||
root = list_to_tree(arr=[1, 2, 3, 4, 5, 6, 7, None, None, None, None, None, None, None, None])
|
||||
root = list_to_tree(arr=[1, 2, 3, 4, 5, 6, 7])
|
||||
print("\n初始化二叉树\n")
|
||||
print_tree(root)
|
||||
|
||||
|
||||
@ -45,7 +45,7 @@ def post_order(root: typing.Optional[TreeNode]):
|
||||
if __name__ == "__main__":
|
||||
# 初始化二叉树
|
||||
# 这里借助了一个从数组直接生成二叉树的函数
|
||||
root = list_to_tree(arr=[1, 2, 3, 4, 5, 6, 7, None, None, None, None, None, None, None, None])
|
||||
root = list_to_tree(arr=[1, 2, 3, 4, 5, 6, 7])
|
||||
print("\n初始化二叉树\n")
|
||||
print_tree(root)
|
||||
|
||||
|
||||
@ -26,39 +26,30 @@ class TreeNode:
|
||||
|
||||
def list_to_tree(arr):
|
||||
"""Generate a binary tree with a list
|
||||
|
||||
Args:
|
||||
arr ([type]): [description]
|
||||
|
||||
Returns:
|
||||
[type]: [description]
|
||||
"""
|
||||
if not arr:
|
||||
return None
|
||||
i = 1
|
||||
root = TreeNode(int(arr[0]))
|
||||
queue = collections.deque()
|
||||
queue.append(root)
|
||||
|
||||
i = 0
|
||||
root = TreeNode(arr[0])
|
||||
queue = collections.deque([root])
|
||||
while queue:
|
||||
node = queue.popleft()
|
||||
i += 1
|
||||
if i >= len(arr): break
|
||||
if arr[i] != None:
|
||||
node.left = TreeNode(int(arr[i]))
|
||||
node.left = TreeNode(arr[i])
|
||||
queue.append(node.left)
|
||||
i += 1
|
||||
if i >= len(arr): break
|
||||
if arr[i] != None:
|
||||
node.right = TreeNode(int(arr[i]))
|
||||
node.right = TreeNode(arr[i])
|
||||
queue.append(node.right)
|
||||
i += 1
|
||||
|
||||
return root
|
||||
|
||||
def tree_to_list(root):
|
||||
"""Serialize a tree into an array
|
||||
|
||||
Args:
|
||||
root ([type]): [description]
|
||||
|
||||
Returns:
|
||||
[type]: [description]
|
||||
"""
|
||||
if not root: return []
|
||||
queue = collections.deque()
|
||||
@ -75,13 +66,6 @@ def tree_to_list(root):
|
||||
|
||||
def get_tree_node(root, val):
|
||||
"""Get a tree node with specific value in a binary tree
|
||||
|
||||
Args:
|
||||
root ([type]): [description]
|
||||
val ([type]): [description]
|
||||
|
||||
Returns:
|
||||
[type]: [description]
|
||||
"""
|
||||
if not root:
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user