iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

Leetcode30天挑戰系列 第 18

Day18-Populating Next Right Pointers in Each Node II

  • 分享至 

  • xImage
  •  

今天的題目為117.Populating Next Right Pointers in Each Node II,今天的題目跟上一題一類似,但今天不是完美二元樹,而是任意的二元樹,這表示節點可能只有左子節點或右子節點,之類。

以下為程式碼:

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 prev = null;

            for (int i = 0; i < size; i++) {
                Node curr = queue.poll();

                if (prev != null) {
                    prev.next = curr;
                }
                prev = curr;

                if (curr.left != null) queue.offer(curr.left);
                if (curr.right != null) queue.offer(curr.right);
            }
        }

        return root;
    }
}

今天的跟前一題相比,困難一點,但還不會到不理解。


上一篇
Day17-Populating Next Right Pointers in Each Node
下一篇
Day19-Pascal's Triangle
系列文
Leetcode30天挑戰30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言