919.完全二叉树插入器

题目描述

完全二叉树 是每一层(除最后一层外)都是完全填充(即,节点数达到最大)的,并且所有的节点都尽可能地集中在左侧。

设计一种算法,将一个新节点插入到一个完整的二叉树中,并在插入后保持其完整。

实现 CBTInserter 类:

    CBTInserter(TreeNode root) 使用头节点为 root 的给定树初始化该数据结构;
    CBTInserter.insert(int v)  向树中插入一个值为 Node.val == val的新节点 TreeNode。使树保持完全二叉树的状态,并返回插入节点 TreeNode 的父节点的值;
    CBTInserter.get_root() 将返回树的头节点。

示例 1:

输入
["CBTInserter", "insert", "insert", "get_root"]
[[[1, 2]], [3], [4], []]
输出
[null, 1, 2, [1, 2, 3, 4]]

 

解释
CBTInserter cBTInserter = new CBTInserter([1, 2]);
cBTInserter.insert(3);  // 返回 1
cBTInserter.insert(4);  // 返回 2
cBTInserter.get_root(); // 返回 [1, 2, 3, 4]

提示:

    树中节点数量范围为 [1, 1000]
    0 <= Node.val <= 5000
    root 是完全二叉树
    0 <= val <= 5000
    每个测试用例最多调用 insert 和 get_root 操作 104 次

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/complete-binary-tree-inserter
 

方法一:

层序遍历,队列

/**
 * 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 CBTInserter {
private:
    TreeNode* root;
public:
    CBTInserter(TreeNode* root) {
        this->root=root;
    }
    
    int insert(int val) {
        queue<TreeNode*> qu;
        qu.push(root);
        while(!qu.empty()){
            TreeNode* t=qu.front();
            qu.pop();
            if(t->left!=nullptr&&t->right!=nullptr){
                qu.push(t->left);
                qu.push(t->right);
            }
            else{
                TreeNode* a=new TreeNode(val);
                if(t->left==nullptr){
                    t->left=a;
                }
                else{
                    t->right=a;
                }
                return t->val;
            }
        }
        return root->val;
    }
    
    TreeNode* get_root() {
        return root;
    }
};

/**
 * Your CBTInserter object will be instantiated and called as such:
 * CBTInserter* obj = new CBTInserter(root);
 * int param_1 = obj->insert(val);
 * TreeNode* param_2 = obj->get_root();
 */

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值