力扣打卡:剑指 Offer II 043. 往完全二叉树添加节点
解题思路
经典的二叉树的层序遍历框架
检查哪一个节点的子节点是否为空
- 如果为空,那么将新节点加进去,然后返回父节点的值
- 如果不为空,那么还是按照平常,加入队列中
代码
/**
* 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 TreeNode root;
public CBTInserter(TreeNode root) {
this.root = root;
}
public int insert(int val) { // 借助队列,进行层序遍历
if(this.root==null) return 0;
Queue<TreeNode> que = new LinkedList<>();
que.offer(this.root);
while(!que.isEmpty()){
int size = que.size();
for(int i=0; i<size; i++){
TreeNode node = que.poll();
if(node.left==null){
node.left = new TreeNode(val);
return node.val;
}else if (node.right==null) {
node.right = new TreeNode(val);
return node.val;
}
que.offer(node.left); que.offer(node.right);
}
}
return 0; // 防止错误
}
public TreeNode get_root() {
return this.root;
}
}
/**
* Your CBTInserter object will be instantiated and called as such:
* CBTInserter obj = new CBTInserter(root);
* int param_1 = obj.insert(v);
* TreeNode param_2 = obj.get_root();
*/