Given two binary search trees root1
and root2
.
Return a list containing all the integers from both trees sorted in ascending order.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4]
Constraints:
- Each tree has at most
5000
nodes. - Each node's value is between
[-10^5, 10^5]
.
方法一:中序遍历两棵树,分别存放在数组arr1、arr2中。怎样把arr1、arr2两数组中的数按从小到大存放在res中???
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { private: void inorderTraverse(TreeNode* root,vector<int>& arr){ if(!root) return; inorderTraverse(root->left,arr); arr.push_back(root->val); inorderTraverse(root->right,arr); } public: vector<int> getAllElements(TreeNode* root1, TreeNode* root2) { vector<int> arr1,arr2,res; inorderTraverse(root1,arr1); inorderTraverse(root2,arr2); int i=0,j=0; while(res.size()!=arr1.size()+arr2.size()){ if(i==arr1.size()) res.push_back(arr2[j++]); else if(j==arr2.size()) res.push_back(arr1[i++]); else if(arr1[i]<arr2[j]) res.push_back(arr1[i++]); else res.push_back(arr2[j++]); } return res; } };
方法二、用栈解决bst的顺序存放。从bst的根结点开始,一直往左遍历,每遍历一个结点就把它放入栈中。比较栈s1和s2栈顶元素的大小,小的(假设为root1)放入res中,,遍历root1的右子树,放入栈中,再比较s1与s2栈顶元素的大小,小的放入res中……
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: vector<int> getAllElements(TreeNode* root1, TreeNode* root2) { stack<TreeNode*> s1,s2; vector<int> res; while(root1||root2||!s1.empty()||!s2.empty()){ while(root1){ s1.push(root1); root1=root1->left; } while(root2){ s2.push(root2); root2=root2->left; } if(s2.empty()||(!s1.empty()&&s1.top()->val<=s2.top()->val)){ root1=s1.top(); s1.pop(); res.push_back(root1->val); root1=root1->right; }else{ root2=s2.top(); s2.pop(); res.push_back(root2->val); root2=root2->right; } } return res; } };