37、类似116-LeetCode117.填充每个节点的下一个右侧节点指针II

题目描述

给定一个二叉树

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。

初始状态下,所有 next 指针都被设置为 NULL。

来源:力扣(LeetCode)

思路:和116类似

116为完美二叉树!每个节点都有两个子节点,或者没有子节点!

1)使用队列,实现层序遍历连接,头节点的处理特殊

2)使用递归,将每一层连接成链表;题目给出的形式也是将每一层连接成了链表;同样116也可以做类似的实现;遍历上层链表,连接下层链表

使用了虚拟头节点,将头节点的处理常规化!

代码

1)使用队列实现,简单!使用了额外空间

class Solution {
    public Node connect(Node root) {
        if(root == null) return root;
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            Node node = queue.poll();
            if(node.left != null) queue.offer(node.left);
            if(node.right != null) queue.offer(node.right);
            for(int i = 1;i < size;i++){
                node.next = queue.peek();
                node = queue.poll();
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
        }
        return root;
    }
}

2)链表实现,省去了元素入队出队的开销

class Solution {
    public Node connect(Node root) {
        //依旧是层序遍历,但是不再要 队列这个辅助的遍历结构
        if(root == null) return root;
        Node cur = root;//一个临时节点改变链表的节点位置,保留root
        cur.next = null;
        while(cur != null){
            //创建一个虚拟头节点,哨兵节点
            Node temp = new Node(0);
            Node pre = temp;
            //遍历连接一层
            while(cur != null){
                if(cur.left != null){
                    pre.next = cur.left;
                    pre = pre.next;//前驱节点后移
                }
                if(cur.right != null){
                    pre.next = cur.right;
                    pre = pre.next;
                }
                cur = cur.next;
            }
            //往下一层移动
            cur = temp.next;
        }
        return root;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值