[LeetCode#117]Populating Next Right Pointers in Each Node II
14136 단어 LeetCode
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:
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
Show Tags
My first solution:
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null)
return;
Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode> ();
int cur = 1;
int next = 0;
queue.offer(root);
while(queue.size() > 0) {
TreeLinkNode temp = queue.poll();
cur--;
if (temp.left != null) {
queue.offer(temp.left);
next++;
}
if (temp.right != null) {
queue.offer(temp.right);
next++;
}
if (cur != 0) {
temp.next = queue.peek();
} else{
temp.next = null;
cur = next;
next = 0;
}
}
}
}
Ugly try:
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null)
return;
int cur = 1;
int next = 0;
TreeLinkNode cur_node = null;
TreeLinkNode pre_node = null;
TreeLinkNode next_start = root;
while (cur != 0) { //if cur == 0, it indicate next layer has no node.
if (pre_node == null) { //a new level
cur_node = next_start;
pre_node = cur_node;
next_start = null;
} else {
cur_node = cur_node.next;
}
cur--;
if (cur_node.left != null) { //note the pre_node indicate the the node at next level
if (next_start == null) {
next_start = cur_node.left;
pre_node = cur_node.left;
next++;
} else{ //since the next_start is not null, it must have a pre node before it in next level.
pre_node.next = cur_node.left;
pre_node = cur_node.left;
next++;
}
}
if (cur_node.right != null) {
if (next_start == null) {
next_start = cur_node.right;
pre_node = cur_node.right;
next++;
} else{
pre_node.next = cur_node.right;
pre_node = cur_node.right;
next++;
}
}
if (cur == 0) {
pre_node.next = null;
cur = next;
next = 0;
pre_node = null;
}
}
}
}
The improved analysis:
This question is not easy, but could be solved in a very elegant way.
The traditional way of achieving level traversal over a tree is to use a Queue. However, in this problem, we are allowed to use constant space. It means we could not use Queue or other container any more.What's the solution?
Think carefully about why we need to use a Queue in level traversal?
It because at each level we don't now the next element!
That's cool. In this problem, we have next attribute in TreeLinkNode, can we use it to achieve the goal?
Absolutely yes!
Key idea: <treat the current level as list!!! It could be very simple!>
At each level, we mainipulate on the next layer(update next pointer), to make it able to use as queue!
Note: at each level, we equal to mainipulate on a linked list. we no longer need to use the ugly counting mechanism! the null pointer is the best way to control traversal!
Invariant:
1. we get the first node of current level from last_head;
while (last_head != null) {
TreeLinkNode cur = last_head;
...
}
2. Now we can work on the current level. using the control condition:
while (cur != null) {
...
}
At current level, the thing we are caring about is next level, since the previous level have already updated the current level.
2.1 we check each node's left child and right child.
2.1.1 once the left child is not null and the next_level's first node is not recorded, the left child is the head of next level's node.(which also means the current level's pre pointer is null)
if (next_head == null) {
next_head = cur.left;
pre = next_head;
}
2.1.2 once the next_level's first node is recorded, it means the left child has pre node in the same level.
...
else{
pre.next = cur.left;
pre = pre.next;
}
2.1.3 the analysis over right child is the same as the above analysis.
3. After we fininsh traversaling the current level, we should update relate varible for next level:
last_head = next_head;
next_head = null;
The improved solution:
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null)
return;
TreeLinkNode last_head = root;
TreeLinkNode next_head = null;
TreeLinkNode pre = null;
while (last_head != null) {
TreeLinkNode cur = last_head;
while (cur != null) {
if (cur.left != null) {
if (next_head == null) {
//we have not reach the first node of next level yet, thus ther is no pre node currently
next_head = cur.left;
pre = next_head;
} else{
pre.next = cur.left;
pre = pre.next;
}
}
if (cur.right != null) {
if (next_head == null) {
next_head = cur.right;
pre = next_head;
} else{
pre.next = cur.right;
pre = pre.next;
}
}
cur = cur.next;
}
last_head = next_head;
next_head = null;
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.