LeetCode每日一题:填充next指针指向右边节点 2

问题描述

Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.

For example,
Given the following binary tree,
1
/
2 3
/ \
4 5 7

After calling your function, the tree should look like:
1 -> NULL
/
2 -> 3 -> NULL
/ \
4-> 5 -> 7 -> NULL

问题分析

跟上一题相比,变成了不完全二叉树,由于采用队列的层次遍历不用考虑是否是满节点,所以上一题的代码也能AC

代码实现

public void connect(TreeLinkNode root) {
        if (root == null) return;
        TreeLinkNode node = null;
        Queue queue = new LinkedList<>();
        queue.offer(root);
        while (queue.isEmpty() == false) {
            int length = queue.size();//存储层次遍历时这层的长度
            for (int i = 0; i < length; i++) {
                node = queue.poll();
                if (i == length - 1) {//最右边的点,next指向null
                    node.next = null;
                } else {
                    node.next = queue.peek();
                }
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
    }

你可能感兴趣的:(LeetCode每日一题:填充next指针指向右边节点 2)