S算法問題: Populating Next Right Pointers in Each Node II
問題描述:
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
算法問題推薦解法來了...
1. iterative way with CONSTANT extra space.
2. iterative way + queue. Contributed by SUN Mian(孫冕).
3. tail recursive solution.
解法(Java)
代碼: |
import java.util.ArrayList;
import java.util.List;
public class PopulatingNextRightPointersinEachNodeII {
public void connect(TreeLinkNode root) {
if (root == null)
return;
TreeLinkNode curLevel = root, cur = root;
curLevel.next = null;
List<TreeLinkNode> nextLevelNodes = new ArrayList<TreeLinkNode>();
while (true) {
while (cur != null) {
if (cur.left != null) {
nextLevelNodes.add(cur.left);
}
if (cur.right != null) {
nextLevelNodes.add(cur.right);
}
cur = cur.next;
}
for (int i = 0; i < nextLevelNodes.size() - 1; i++) {
nextLevelNodes.get(i).next = nextLevelNodes.get(i + 1);
}
if (nextLevelNodes.size() > 0) {
curLevel = nextLevelNodes.get(0);
cur = curLevel;
nextLevelNodes.clear();
} else {
break;
}
}
}
}
|
S算法問題: Populating Next Right Pointers in Each Node
問題描述:
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
算法問題推薦解法來了...
1. Iterative: Two 'while' loops: root->leaf and left->right.
2. Iterative: Queue. Use extra space.
3. Recursive: DFS. Defect: Use extra stack space for recursion.
解法(Java)
代碼: |
public class PopulatingNextRightPointersinEachNode {
public void connect(TreeLinkNode root) {
if (root == null)
return;
TreeLinkNode curLevel = root;
TreeLinkNode cur = root;
curLevel.next = null;
while (true) {
while (cur != null) {
if (cur.left != null) {
cur.left.next = cur.right;
if (cur.next != null) {
cur.right.next = cur.next.left;
}
}
cur = cur.next;
}
if (curLevel.left != null) {
curLevel = curLevel.left;
cur = curLevel;
} else {
break;
}
}
}
}
|
S算法問題: Recover Binary Search Tree
問題描述:
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?