其他分享
首页 > 其他分享> > 【leetcode】1305. All Elements in Two Binary Search Trees 二叉搜索树

【leetcode】1305. All Elements in Two Binary Search Trees 二叉搜索树

作者:互联网

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]

Example 2:

Input: root1 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]

   这道题基本解法是分别遍历这两个BST,得到两个arr,然后拼接之后在进行排序,输出递增的arr。但这样并没有利用到BST的特点,bst中最小的元素应该在左子树上,按照大佬的解法,可以用栈先存储所有的左子树,然后从底层往顶层检索。


class Solution {
public:
    vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
        vector<int>vecRes;
        stack<TreeNode*> staR1,staR2;
        // bst 左子树的节点的值都小于根节点
        while(root1 ||  root2 || !staR1.empty() || !staR2.empty()){
            
            while(root1){
                staR1.push(root1);
                root1=root1->left;
            }
            while(root2){
                staR2.push(root2);
                root2=root2->left;
            }
            if(staR2.empty()|| (!staR1.empty() && staR1.top()->val<=staR2.top()->val)){
                root1=staR1.top();
                staR1.pop(); // pop smallest element in this stack
                vecRes.push_back(root1->val);
                root1=root1->right;
            }
            else{
                root2=staR2.top();
                staR2.pop();
                vecRes.push_back(root2->val);
                root2=root2->right;
            }
        }
        return vecRes;
        
    }
};

 

标签:1305,Search,Elements,staR1,staR2,push,root1,empty,root2
来源: https://www.cnblogs.com/aalan/p/15849602.html