-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
chenzhengwei
committed
Feb 27, 2017
1 parent
312fd79
commit 048e3da
Showing
2 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
#116. Populating Next Right Pointers in Each Node | ||
[题目链接](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/?tab=Description) | ||
```java | ||
public class Solution { | ||
public void connect(TreeLinkNode root) { | ||
if (root == null) { | ||
return; | ||
} | ||
// 利用队列的性质,采用广度优先便利 | ||
LinkedList<TreeLinkNode> ll = new LinkedList<>(); | ||
ll.add(root); | ||
// 以层为单位进行循环 | ||
while (ll.size() != 0) { | ||
int n = ll.size(); | ||
TreeLinkNode node = ll.pop(); | ||
// 层内循环 | ||
for (int i = 0; i < n; i++) { | ||
if (node.left != null) { | ||
ll.addLast(node.left); | ||
ll.addLast(node.right); | ||
} | ||
// 如果是层的最后一个,next设为null | ||
if (i < n - 1) { | ||
TreeLinkNode nextNode = ll.pop(); | ||
node.next = nextNode; | ||
node = nextNode; | ||
} else { | ||
node.next = null; | ||
} | ||
} | ||
} | ||
} | ||
} | ||
``` |