919. 完全二叉树插入器

919. 完全二叉树插入器

解题思路

  • 创建一个队列 记录完全二叉树底部可以进行插入的节点
  • 对二叉树进行BFS 找到可以进行插入的节点
  • 队列出队,创建新节点进行插入

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class CBTInserter {
    
    
    // 创建一个队列 记录完全二叉树底部可以进行插入的节点
    private Queue<TreeNode> temp = new LinkedList<>();
    private TreeNode root;

    public CBTInserter(TreeNode root) {
    
    
        // 创建一个完全二叉树
        this.root = root;
        // 进行BFS 找到可以插入的节点
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while(!q.isEmpty()){
    
    
            TreeNode cur = q.poll();
            if(cur.left != null){
    
    
                q.offer(cur.left);
            }
            if(cur.right != null){
    
    
                q.offer(cur.right);
            }
            if(cur.left == null || cur.right == null){
    
    
                temp.offer(cur);// 添加到队列
            }
        }
    }
    
    public int insert(int val) {
    
    
        // 插入节点
        TreeNode node = new TreeNode(val);
        TreeNode cur = temp.peek();// 取出队列的节点

        // 进行插入
        if(cur.left == null){
    
    
            cur.left = node;
        }else if(cur.right == null){
    
    
            cur.right = node;

             // 插入结束之后  出队
            temp.poll();
        }
       

        // 新节点 的左右节点也是
        temp.offer(node);
        return cur.val;
    }
    
    public 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();
 */

猜你喜欢

转载自blog.csdn.net/qq_44653420/article/details/132508901
今日推荐