Create 116. Populating Next Right Pointers in Each Node.md

This commit is contained in:
唐树森 2019-06-11 23:58:58 +08:00 committed by GitHub
parent 0ad5b9e56a
commit a4bb4a89aa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,58 @@
# [116. Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)
# 思路
题目要求将满二叉树同一层的节点用指针串起来要求空间复杂度O(1)。
## 思路一、递归
最好想的还是递归: 如果root的左右子树都已经串好了的话那么我们只需要将左子树每一层的最右边的节点的next指向右子树对应层最左边节点即可。
## 思路二、非递归
由于next指针将每一层的节点都串起来了所以我们可以很方便地从第一层的最左边节点开始访问第二层的所有节点、从第二层的最左边节点开始访问第三层的所有节点...
因此我们可以用这个思路从上往下依次将每一层串起来。我们用start表示每层的最左边节点如果该层不是最后一层那么我们应该将下一层所有节点串起来。
该方法真正实现了空间复杂度O(1)。
# C++
## 思路一
``` C++
class Solution {
public:
Node* connect(Node* root) {
if(root == NULL) return NULL; // 递归出口
Node *p_left = connect(root -> left); // 左子树都已经串好了
Node *p_right = connect(root -> right); // 右子树都已经串好了
// 将左子树每一层的最右边的节点的next指向右子树对应层最左边节点
while(p_left){
p_left -> next = p_right;
p_left = p_left -> right;
p_right = p_right -> left;
}
return root;
}
};
```
## 思路二
``` C++
public:
Node* connect(Node* root) {
if(root == NULL) return NULL;
Node *start = root, *p = NULL;
while(start){
p = start;
// p从每层开始节点起往右移动
while(p){
if(p -> left) { // 如果不是最后一层
p -> left -> next = p -> right;
if(p -> next) // 如果不是本层的最后一个节点
p -> right -> next = p -> next -> left;
}
p = p -> next;
}
start = start -> left; // 处理下一层
}
return root;
}
};
```