leetcode1305 All Elements in Two Binary Search Trees

 1 """
 2 Given two binary search trees root1 and root2.
 3 Return a list containing all the integers from both trees sorted in ascending order.
 4 Example 1:
 5 Input: root1 = [2,1,4], root2 = [1,0,3]
 6 Output: [0,1,1,2,3,4]
 7 Example 2:
 8 Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
 9 Output: [-10,0,0,1,2,5,7,10]
10 Example 3:
11 Input: root1 = [], root2 = [5,1,7,0,2]
12 Output: [0,1,2,5,7]
13 Example 4:
14 Input: root1 = [0,-10,10], root2 = []
15 Output: [-10,0,10]
16 Example 5:
17 Input: root1 = [1,null,8], root2 = [8,1]
18 Output: [1,1,8,8]
19 """
20 class TreeNode:
21     def __init__(self, x):
22         self.val = x
23         self.left = None
24         self.right = None
25 
26 """
27 此题提供三种思路,与leetcode98类似,https://www.cnblogs.com/yawenw/p/12376942.html
28 第一种是层次遍历,
29 然后对存入的值sorted排序
30 传送门:https://blog.csdn.net/qq_17550379/article/details/103838538
31 """
32 class Solution1:
33     def getAllElements(self, root1, root2):
34         q, res = [root1, root2], []
35         while q:
36             cur = q.pop(0)
37             if cur:
38                 res.append(cur.val)
39                 if cur.left != None:
40                     q.append(cur.left)
41                 if cur.right != None:
42                     q.append(cur.right)
43         return sorted(res)
44 
45 """
46 第二种是利用二叉搜索树的条件,
47 对两个树分别中序遍历。这样两个list分别有序
48 再进行归并排序
49 """
50 class Solution2:
51     def getAllElements(self, root1, root2):
52         q1, q2 = [], []
53         res = []
54         # 中序遍历
55         def inorder(root, q):
56             if root:
57                 inorder(root.left, q)
58                 q.append(root.val)
59                 inorder(root.right, q)
60         inorder(root1, q1)
61         inorder(root2, q2)
62         # 归并排序的方法
63         while q1 or q2:
64             if not q1:
65                 res += q2
66                 break
67             if not q2:
68                 res += q1
69                 break
70             else:
71                 res.append(q1.pop(0) if q1[0] < q2[0] else q2.pop(0))
72         return res
73 
74 """
75 第三种是:
76 先中序遍历(代替层次遍历)
77 再sorted(代替归并排序)
78 """
79 class Solution3:
80     def getAllElements(self, root1, root2):
81         res = []
82         def inOrder(root):
83             if root:    #!!!bug 没有写次if语句
84                 inOrder(root.left)
85                 res.append(root.val)
86                 inOrder(root.right)
87         inOrder(root1)
88         inOrder(root2)
89         return sorted(res)

 

posted @ 2020-02-08 19:52  yawenw  阅读(133)  评论(0编辑  收藏  举报