0
点赞
收藏
分享

微信扫一扫

剑指offer_043 往完全二叉树添加节点

驚鴻飛雪 2022-01-13 阅读 51

题目:

示例 1:

示例 2:

提示:

代码:

package jianzhi;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class offer_43 {

    // 初始化节点
    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 {

        // 根节点
        TreeNode root;
        // 初始化一个用来存储子节点未满的节点的队列
        Queue<TreeNode> notFull = new LinkedList<>();

        // 把子节点未满的节点放入队列
        public CBTInserter(TreeNode root) {

            //初始化根节点
            this.root = root;

            // 初始化一个队列用来存储子节点已满的队列
            Queue<TreeNode> temp = new LinkedList<>();
            temp.offer(root);
            /**
             * 1、把根节点加入队列
             * 2、取出队列中的队头节点,如果子节点不满,则将此节点加入
             * 3、然后依次把该节点的左右子节点加入队列
             * 4、重复步骤二和步骤三,直到队列为空,此时所有不满的节点都已经加入了 notFull 队列
             */
            while (!temp.isEmpty()) {
                TreeNode t = temp.poll();
                if (t.left == null || t.right == null) {
                    // 把不满的节点放入temp
                    notFull.offer(t);
                }
                if (t.left != null) {
                    temp.offer(t.left);
                }
                if (t.right != null) {
                    temp.offer(t.right);
                }
            }

        }

        /**
         * 加入节点返回父节点的值
         * 1、先查看队头节点的左子树是否为空,如果为空则把该节点加入到左子树
         * 2、左子树不为空的话则把该节点加入到队头节点,此时队头节点的子节点已满,移出 notFull 队列
         * @param v
         * @return
         */
        public int insert(int v) {
            TreeNode t = notFull.peek();
            if (t.left == null) {
                t.left = new TreeNode(v);
                notFull.offer(t.left);
            } else {
                t.right = new TreeNode(v);
                notFull.poll();
                notFull.offer(t.right);
            }
            return t.val;
        }

        public TreeNode get_root() {
            return this.root;
        }
    }

}

 解题思路:

参考链接:

 力扣

举报

相关推荐

0 条评论