• API
• FAQ
• Tools
• Archive
SHARE
TWEET

Untitled

a guest Sep 12th, 2019 118 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import Queue
2. import pdb
3.
4. class BinTree:
5.
6.     val = 0
7.     left = None
8.     right = None
9.
10.     def __init__(self,_val):
11.         self.val = _val
12.         self.left = None
13.         self.right = None
14.
15. def createBTNode(val):
16.     return BinTree(val)
17.
18.
19.
20. def arr_to_btree(input_array):
21.
22.     i = 0
23.     root = createBTNode(input_array[0])
24.     node_queue = Queue.Queue(maxsize=100)
25.     node_queue.put(root)
26.
27.     while not node_queue.empty():
28.         new_tree = node_queue.get()
29.
30.         if 2*i+1 >= len(input_array):
31.             break
32.
33.         left_node = createBTNode(input_array[2*i+1])
34.         new_tree.left = left_node
35.         node_queue.put(left_node)
36.
37.         if 2*i+2 >= len(input_array) or input_array[2*i+1] is None:
38.             break
39.         right_node = createBTNode(input_array[2*i+2])
40.         new_tree.right = right_node
41.
42.         if input_array[2*i+2] is not None:
43.             node_queue.put(right_node)
44.         i+=1
45.     return root
46.
47.
48.
49. def print_tree(root):
50.     if root is not None:
51.         print(root.val)
52.         print_tree(root.left)
53.         print_tree(root.right)
54.
55.
56. def main():
57.     arr = [2,3,6,None,8,2,3,3,1]
58.     pdb.set_trace()
59.     root = arr_to_btree(arr)
60.     print_tree(root)
61.
62.
63. main()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top