LeetCode学习笔记(2) 第1305题 All Elements in Two Binary Search Trees

题目: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.
在这里插入图片描述
在这里插入图片描述

分析

Solution1:Collect and sort
	Treat as random trees, collect elements into one array and sort it.
	Time complexity:O(nlogn)
	Space complexity:O(n)
Solution 2: Inorder traversal + merge
	2.1 two traversals and then merge
	2.2 merging while traversal
		 do inorder with a stack ,the top of the stack is the smallest element of the tree.
	Time complexity:O(n)
	Space complexity:O(n)

流程

Solution 2.1:
	由于BST的特殊性质,Inorder之后,是有序序列, 所以可以分别将两棵BST,
	遍历到vector中,运用merge思想,对它们进行排序返回.排序复杂度为O(nlogn)
Solution 2.2:
	将traversal和merge合并到一起做

代码

Solution1(python)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def getAllElements(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: List[int]
        """
        s1 = []
        s2 = []
        self.traversal(root1, s1)
        self.traversal(root2, s2)
        s1.extend(s2)
        s1.sort()
        return s1
    
    def traversal(self, root, temp):
        if root is None:
            return
        self.traversal(root.left, temp)
        temp.append(root.val)
        self.traversal(root.right, temp)

Solution 2.1(c++):

/**
 * 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) {
    vector<int> a1;
    vector<int> a2;
    traverse(root1, a1);
    traverse(root2, a2);
    vector<int> result;
    int j = 0;
    int i = 0;
    while(result.size() != a1.size() + a2.size())
    {
        if(i == a1.size())
            result.push_back(a2[j++]);
        else if(j == a2.size())
            result.push_back(a1[i++]);
        else
            if(a1[i] < a2[j])
                result.push_back(a1[i++]);
            else
                result.push_back(a2[j++]);
    }
    return result;
    }
private:
    void traverse(TreeNode* root, vector<int>& a)
    {
        if(root==NULL)
            return;        
        traverse(root->left, a);
        a.push_back(root->val);
        traverse(root->right, a);
    }
};

Solution 2.1(python)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def getAllElements(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: List[int]
        """
        s1 = []
        s2 = []
        self.traversal(root1, s1)
        self.traversal(root2, s2)
        res = []
        i = 0
        j = 0
        while len(res) != len(s1) + len(s2):
            if i == len(s1):
                res.append(s2[j])
                j += 1
            elif j == len(s2):
                res.append(s1[i])
                i+=1
            else:
                if s1[i] < s2[j]:
                    res.append(s1[i])
                    i+=1
                else:
                    res.append(s2[j])
                    j+=1
        return res
        
    def traversal(self, root, s):
        if root is None:
            return
        self.traversal(root.left, s)
        s.append(root.val)
        self.traversal(root.right, s)
        

Solution 2.2(c++)

/**
 * 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) {
    function<void(TreeNode*, stack<TreeNode*>&)> smallest = [&](TreeNode* root, stack<TreeNode*>& s){
        if(root==NULL)return;
        s.push(root);
        smallest(root->left, s);
    };
    stack<TreeNode*> s1;
    stack<TreeNode*> s2;
    smallest(root1, s1);
    smallest(root2, s2);
    vector<int> ans;
    while(!s1.empty() || !s2.empty())
    {
        stack<TreeNode*>& s = s1.empty()? s2 : s2.empty()?s1 : s1.top()->val < s2.top()->val ?s1:s2;
        TreeNode* n = s.top(); s.pop();
        ans.push_back(n->val);
        smallest(n->right, s);
    }
    return ans;
    }
};

小知识点

python函数
在这里插入图片描述
python list方法
在这里插入图片描述
c++中function的理解:LINK

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值