题目描述:
给你 root1 和 root2 这两棵二叉搜索树。
请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.
链接: https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees/.
解题思路:
深度优先搜索,没什么好说的,把元素存储在result里,先搜索root1,再搜索root2.
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:
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
vector<int> result;
bfs(root1,result);
bfs(root2,result);
sort(result.begin(),result.end());
return result;
}
void bfs(TreeNode* root,vector<int>& result){
if(root==NULL) return;
result.push_back(root->val);
bfs(root->left,result);
bfs(root->right,result);
}
};