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]

题目:将两个二叉搜索树的元素按从小到大排列。

思路:inorder traversal的变体。两个二叉搜索树一起inorder遍历。代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
        stack<TreeNode*> s1, s2;
        TreeNode* n1 = root1, *n2 = root2;
        vector<int> res;
        while(!s1.empty() || !s2.empty() || n1 || n2){
            while(n1){
                s1.push(n1);
                n1 = n1->left;
            }
            while(n2){
                s2.push(n2);
                n2 = n2->left;
            }
            int choose = 1;
            if(s1.empty()) choose = 2;
            else if(s2.empty()) choose = 1;
            else if(s2.top()->val <= s1.top()->val) choose = 2;
            else choose = 1;
            
            if(choose == 1){
                res.push_back(s1.top()->val);
                n1 = s1.top()->right;
                s1.pop();
            } else{
                res.push_back(s2.top()->val);
                n2 = s2.top()->right;
                s2.pop();
            }
        }
        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值