秋招笔试专栏——复盘

66 阅读1分钟

08/23腾讯音乐笔试T2

题目

image.png 这道题说白了就是一个二叉树的补全,把一个普通的二叉树补成完全二叉树。

代码

/**
 * 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:
    int maxVal = 1;
    void dfs(TreeNode* root, int num) {
        if(root == nullptr) return;

        root->val = num;
        maxVal = max(maxVal, num);
        dfs(root->left, num * 2);
        dfs(root->right, num * 2 + 1);
    }

    void bfs(TreeNode* root) {
        queue<TreeNode*> que;
        if(root) que.push(root);
        while(!que.empty()) {
            int size = que.size();
            for(int i = 0; i < size; i++) {
                auto p = que.front(); que.pop();
                if(!p->left && p->val * 2 < maxVal) {
                    p->left = new TreeNode(p->val * 2);
                }
                if(p->left) que.push(p->left);
                if(!p->right && p->val * 2 + 1 < maxVal) {
                    p->right = new TreeNode(p->val * 2 + 1);
                }
                if(p->right) que.push(p->right);
            }
        }
    }
    
    void rightSideView(TreeNode* root) {
        dfs(root, 1);
        bfs(root);
        //再用一个遍历把值都改为1即可
    }
};

思路:

  1. 先修改二叉树的值,按照完全二叉树去给每个节点编号,根节点从1开始,并记录最后一个节点的值;
  2. BFS遍历二叉树,当某节点的子节点为空且它的值小于最大节点的时候则生成节点并连接上
  3. 把每个节点的值修改回1