leetcode *117. 填充每个节点的下一个右侧节点指针 II(2020.9.28)& *116. 填充每个节点的下一个右侧节点指针(2020.10.15)

【题目】*117. 填充每个节点的下一个右侧节点指针 II & *116. 填充每个节点的下一个右侧节点指针

这两题的区别是,116题是完全二叉树,117题是普通二叉树,下面以普通二叉树作答
给定一个二叉树

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。

进阶:
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。

示例:
在这里插入图片描述

输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。

提示:
树中的节点数小于 6000
-100 <= node.val <= 100

【解题思路1】BFS

从右到左BFS遍历,借助队列

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

改进:无需借助队列
已经填充好的每一层结点,其实已经组成了一个单向的链表,只要获取下一层链表的头结点,即可遍历下一层所有结点,所以只需要使用一个变量指向头节点。

public class Solution {
    public Node connect(Node root) {
        Node cur = root;
        while (cur != null) {
            //head.next指向下一层层头
            Node head = new Node(0);
            Node temp = head;
            //遍历当前层所有结点,并将下一层结点串成一个单链表
            while (cur != null) {
                if (cur.left != null) {
                    temp.next = cur.left;
                    temp = temp.next;
                }
                if (cur.right != null) {
                    temp.next = cur.right;
                    temp = temp.next;
                }
                //访问本层下一个结点
                cur = cur.next;
            }
            //指向下一层头结点
            cur = head.next;
        }
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值