mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
add 117
This commit is contained in:
parent
0ad5b9e56a
commit
47ce0a97a2
@ -0,0 +1,46 @@
|
|||||||
|
# [117. Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)
|
||||||
|
|
||||||
|
# 思路
|
||||||
|
题目要求将二叉树同一层的节点用指针串起来,要求空间复杂度O(1)。
|
||||||
|
这题是[116](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)的升级版,116中的二叉树是满二叉树,比较简单,但思路其实也是类似的,可先参考[116题解](https://github.com/ShusenTang/LeetCode/blob/master/solutions/116.%20Populating%20Next%20Right%20Pointers%20in%20Each%20Node.md)。
|
||||||
|
## 思路一
|
||||||
|
最好想的还是递归: 如果root的左右子树都已经串好了的话,那么我们只需要将左子树每一层的最右边的节点的next指向右子树对应层最左边节点即可。
|
||||||
|
|
||||||
|
## 思路二
|
||||||
|
|
||||||
|
# C++
|
||||||
|
## 思路一
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
Node* connect(Node* root) {
|
||||||
|
if(root == NULL) return NULL;
|
||||||
|
Node *start_left = connect(root -> left);
|
||||||
|
Node *start_right = connect(root -> right);
|
||||||
|
while(start_left && start_right){
|
||||||
|
Node *last_left = start_left;
|
||||||
|
while(last_left -> next) last_left = last_left -> next;
|
||||||
|
last_left -> next = start_right;
|
||||||
|
|
||||||
|
while(!start_left->left &&
|
||||||
|
!start_left->right &&
|
||||||
|
start_left -> next != start_right)
|
||||||
|
start_left = start_left -> next;
|
||||||
|
if(start_left -> left) start_left = start_left -> left;
|
||||||
|
else start_left = start_left -> right;
|
||||||
|
|
||||||
|
|
||||||
|
while(!start_right->left &&
|
||||||
|
!start_right->right &&
|
||||||
|
start_right -> next)
|
||||||
|
start_right = start_right -> next;
|
||||||
|
if(start_right -> left) start_right = start_right -> left;
|
||||||
|
else start_right = start_right -> right;
|
||||||
|
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 思路二
|
Loading…
Reference in New Issue
Block a user