mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
更新0116.填充每个节点的下一个右侧节点指针java注释及代码规范
This commit is contained in:
@ -133,14 +133,14 @@ public:
|
||||
// 递归法
|
||||
class Solution {
|
||||
public void traversal(Node cur) {
|
||||
if(cur == null) return;
|
||||
if(cur.left != null) cur.left.next = cur.right;
|
||||
if(cur.right != null){
|
||||
if(cur.next != null) cur.right.next = cur.next.left;
|
||||
if (cur == null) return;
|
||||
if (cur.left != null) cur.left.next = cur.right; // 操作1
|
||||
if (cur.right != null) {
|
||||
if(cur.next != null) cur.right.next = cur.next.left; //操作2
|
||||
else cur.right.next = null;
|
||||
}
|
||||
traversal(cur.left);
|
||||
traversal(cur.right);
|
||||
traversal(cur.left); // 左
|
||||
traversal(cur.right); //右
|
||||
}
|
||||
public Node connect(Node root) {
|
||||
traversal(root);
|
||||
@ -152,26 +152,26 @@ class Solution {
|
||||
// 迭代法
|
||||
class Solution {
|
||||
public Node connect(Node root) {
|
||||
if(root == null) return root;
|
||||
if (root == null) return root;
|
||||
Queue<Node> que = new LinkedList<Node>();
|
||||
que.offer(root);
|
||||
Node nodePre = null;
|
||||
Node node = null;
|
||||
while(!que.isEmpty()){
|
||||
while (!que.isEmpty()) {
|
||||
int size = que.size();
|
||||
for(int i=0; i<size; i++){ // 开始每一层的遍历
|
||||
if(i == 0){
|
||||
for (int i=0; i<size; i++) { // 开始每一层的遍历
|
||||
if (i == 0) {
|
||||
nodePre = que.peek(); // 记录一层的头结点
|
||||
que.poll();
|
||||
node = nodePre;
|
||||
}else{
|
||||
} else {
|
||||
node = que.peek();
|
||||
que.poll();
|
||||
nodePre.next = node; // 本层前一个节点next指向本节点
|
||||
nodePre = nodePre.next;
|
||||
}
|
||||
if(node.left != null) que.offer(node.left);
|
||||
if(node.right != null) que.offer(node.right);
|
||||
if (node.left != null) que.offer(node.left);
|
||||
if (node.right != null) que.offer(node.right);
|
||||
}
|
||||
nodePre.next = null; // 本层最后一个节点指向null
|
||||
}
|
||||
|
Reference in New Issue
Block a user