[LeetCode 107,108][简单]二叉树的层次遍历 II/将有序数组转换为二叉搜索树

107,二叉树的层次遍历 II
题目链接

class Solution {
public:
    typedef pair<TreeNode *,int> pii;
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> ans;
        if(root == NULL)return ans;
        queue<pii> mq;vector<int>p;
        mq.push(make_pair(root, 0));
        int d=0;
        while(!mq.empty()){
            pii q = mq.front();
            mq.pop();
            if(q.second != d){
                ans.emplace_back(p);
                d = q.second;
                p.clear();
            }
            p.emplace_back(q.first -> val);
            if(q.first->left)mq.push(make_pair(q.first->left, q.second + 1));
            if(q.first->right)mq.push(make_pair(q.first->right, q.second + 1));
        }
        if(p.size())ans.emplace_back(p);
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

108.将有序数组转换为二叉搜索树
题目链接
dfs建树,类似的思想还能体现在线段树上。

class Solution {
public:
    TreeNode *build(int l, int r, vector<int>& mv){
        if(r<l)return NULL;
        int m = (l + r) >> 1;
        TreeNode *root = new TreeNode(mv[m]);
        root->left = build(l, m-1, mv);
        root->right = build(m+1, r, mv);
        return root;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return build(0,nums.size()-1, nums);
    }
};

你可能感兴趣的:(LeetCode,#,LeetCode,-,简单)