116. Populating Next Right Pointers in Each Node

本文介绍三种填充完全二叉树中节点Next指针的方法:使用队列进行层次遍历、利用双指针进行层次遍历以及利用递归实现每一层的Next指针填充。每种方法都附带了详细的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、题目

  1、审题

  2、分析

    给出一个完全二叉树,添加二叉树的 next 指针指向。

 

二、解答

  1、思路: 

    方法一、

      采用队列进行层次遍历,遍历时添加 next 指针。

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

  

  方法二、

    利用两个指针进行层次遍历,添加 next 指针

    public void connect(TreeLinkNode root) {
        if(root == null)
            return;
        TreeLinkNode pre = root;
        TreeLinkNode cur;
        while(pre.left != null) {
            cur = pre;
            while(cur != null) {
                cur.left.next = cur.right;
                if(cur.next != null)
                    cur.right.next = cur.next.left;
                cur = cur.next;
            }
            pre = pre.left;
        }
    }

  

  方法三、

    利用递归实现每一层的 next 指针。

    public void connect(TreeLinkNode root) {
        if(root == null)
            return;
        
        if(root.left != null) {
            root.left.next = root.right;
            if(root.next != null)
                root.right.next = root.next.left;
        }
        connect(root.left);
        connect(root.right);
    }

 

转载于:https://www.cnblogs.com/skillking/p/9745232.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值