Skip to content

Update 116 #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 11 additions & 33 deletions src/main/java/com/fishercoder/solutions/_116.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,40 +39,18 @@ public static class Solution1 {
//credit: https://discuss.leetcode.com/topic/1106/o-1-space-o-n-complexity-iterative-solution
//based on level order traversal
public void connect(TreeLinkNode root) {
if(root == null)
return;

TreeLinkNode head = null; //head of the next level
TreeLinkNode prev = null; //the leading node on the next level
TreeLinkNode curr = root; //current node of current level

while (curr != null) {
while (curr != null) { //iterate on the current level
//left child
if (curr.left != null) {
if (prev != null) {
prev.next = curr.left;
} else {
head = curr.left;
}
prev = curr.left;
}
//right child
if (curr.right != null) {
if (prev != null) {
prev.next = curr.right;
} else {
head = curr.right;
}
prev = curr.right;
}
//move to next node
curr = curr.next;
}
//move to next level
curr = head;
head = null;
prev = null;
}
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);
}
}

}
}