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

问题描述

Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.
Initially, all next pointers are set toNULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

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

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

问题分析

这道题让我们给每个节点一个next指针指向它右边的节点,其实就是考虑层次遍历即可,采用队列实现

代码实现

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指针指向右边节点 1)