2020/11/12 116. 填充每个节点的下一个右侧节点指针

利用BFS遍历整棵树,利用队列的size()方法,将节点分组,一一设置下一节点

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

    }
}

省空间升级版

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

    }
}

在进行时间复杂度分析时,由于需要不断进行入队和出队操作,使得整个算法的时间效率不是很高,可以省去队列,而是采用指针记录的方法,提高运算效率,代码如下:

class Solution {
    public Node connect(Node root) {
        if(root==null){
            return root;
        }
        Node cur=root;
        while(cur!=null){
            Node dummy=new Node();
            Node pre=dummy;
            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=dummy.next;
        }
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值