Skip to content

Commit

Permalink
a116
Browse files Browse the repository at this point in the history
  • Loading branch information
chenzhengwei committed Feb 27, 2017
1 parent 312fd79 commit 048e3da
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ leetcode 题解

[110. Balanced Binary Tree](Solution/101-150/110.md)

[116. Populating Next Right Pointers in Each Node](Solution/101-150/116.md)

[119. Pascal's Triangle II](Solution/101-150/119.md)

[121. Best Time to Buy and Sell Stock](Solution/101-150/121.md)
Expand Down
34 changes: 34 additions & 0 deletions Solution/101-150/116.md
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;
}
}
}
}
}
```

0 comments on commit 048e3da

Please sign in to comment.