上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
}
};
python3 解法, 执行用时: 296 ms, 内存消耗: 24.1 MB, 提交时间: 2022-11-11 11:58:15
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
def inorder(node: TreeNode, res: List[int]):
if node:
inorder(node.left, res)
res.append(node.val)
inorder(node.right, res)
nums1, nums2 = [], []
inorder(root1, nums1)
inorder(root2, nums2)
merged = []
p1, n1 = 0, len(nums1)
p2, n2 = 0, len(nums2)
while True:
if p1 == n1:
merged.extend(nums2[p2:])
break
if p2 == n2:
merged.extend(nums1[p1:])
break
if nums1[p1] < nums2[p2]:
merged.append(nums1[p1])
p1 += 1
else:
merged.append(nums2[p2])
p2 += 1
return merged
python3 解法, 执行用时: 276 ms, 内存消耗: 24 MB, 提交时间: 2022-11-11 11:56:15
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
def inorder(node: TreeNode) -> List[int]:
nonlocal arr
if node:
inorder(node.left)
arr.append(node.val)
inorder(node.right)
arr = list()
inorder(root1)
inorder(root2)
arr.sort()
return arr