/**
* 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 doit(TreeNode* now,vector<int>& v){
if(now->left != NULL) doit(now->left,v);
v.push_back(now->val);
if(now->right != NULL) doit(now->right,v);
}
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
vector<int> treeA;
vector<int> treeB;
if(root1 != NULL) doit(root1,treeA);
if(root2 != NULL) doit(root2,treeB);
vector<int> ans(treeA.size()+treeB.size(),0);
int a = 0;
int b = 0;
int loc = 0;
while(a<treeA.size() && b<treeB.size()){
if(treeA[a] <= treeB[b]) ans[loc++] = treeA[a++];
else ans[loc++] = treeB[b++];
}
while(a<treeA.size()) ans[loc++] = treeA[a++];
while(b<treeB.size()) ans[loc++] = treeB[b++];
return ans;
}
};
No.174 - LeetCode1305 - 合并两个搜索树
最新推荐文章于 2024-03-26 22:36:59 发布
本文介绍了一种在C++中实现的二叉树节点遍历算法,并通过一个Solution类展示了如何将两个二叉树的所有元素进行中序遍历并合并成一个有序数组的过程。该方法首先对每个树进行递归的中序遍历,收集所有节点值到各自的数组中,然后将这两个数组合并为一个有序数组。
145

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



