给你 root1 和 root2 这两棵二叉搜索树。
请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.
示例 1:

输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]
示例 2:
输入:root1 = [0,-10,10], root2 = [5,1,7,0,2]
输出:[-10,0,0,1,2,5,7,10]
示例 3:
输入:root1 = [], root2 = [5,1,7,0,2]
输出:[0,1,2,5,7]
示例 4:
输入:root1 = [0,-10,10], root2 = []
输出:[-10,0,10]
示例 5:

输入:root1 = [1,null,8], root2 = [8,1]
输出:[1,1,8,8]
提示:
- 每棵树最多有
5000个节点。 - 每个节点的值在
[-10^5, 10^5]之间。
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* root, vector<int>& res)
{
if(root)
{
res.push_back(root->val);
dfs(root->left,res);
dfs(root->right,res);
}
}
vector<int> getAllElements(TreeNode* root1, TreeNode* root2)
{
vector<int> res;
dfs(root1,res);
dfs(root2,res);
sort(res.begin(),res.end());
return res;
}
};

本文介绍了一种算法,用于合并两棵二叉搜索树的所有整数,并将其按升序排序。通过深度优先搜索遍历两棵树,收集所有节点值,然后对收集到的值进行排序,最终返回排序后的整数列表。
631

被折叠的 条评论
为什么被折叠?



