Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
public TreeNode connect(TreeNode root) { if (root == null) { ...

Avinash Agarwal

Apr 5, 2022

public TreeNode connect(TreeNode root) {

if (root == null) { return root; }

// Start with the root node. There are no next pointers // that need to be set up on the first level Node leftmost = root;

// Once we reach the final level, we are done while (leftmost.left != null) {

// Iterate the "linked list" starting from the head // node and using the next pointers, establish the // corresponding links for the next level Node head = leftmost;

while (head != null) {

// CONNECTION 1 head.left.next = head.right;

// CONNECTION 2 if (head.next != null) { head.right.next = head.next.left; }

// Progress along the list (nodes on the current level) head = head.next; }

// Move onto the next level leftmost = leftmost.left; }

return root; }

This is a solution with O(1) space.

0

0

Comments
Comments
Design Gurus
Design Gurus4 years ago

This code gives NullPointerException when run on the given Example-2. Can you please check your code?

A
Avinash Agarwal4 years ago

That is true. the solution is for a perfect binary tree. This may work better for this version,

Node prev, leftMost;

public Node connect(Node root) { leftMost = root; while (leftMost != null) { Node head = leftMost; prev = leftMost = null; while (head != null) { conne...

On this page