## Wednesday, November 12, 2014

### [LeetCode] Populating Next Right Pointers in Each Node I, II

Populating Next Right Pointers in Each Node I

Given a binary tree
```    struct TreeLinkNode {
}
```
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```

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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32``` ```class Solution { public: void connect(TreeLinkNode *root) { while(root && !root->left && !root->right) root = root->next; if(!root) return; TreeLinkNode *leftMost = root->left ? root->left : root->right; TreeLinkNode *cur = leftMost; while(root) { if(cur==root->left) { if(root->right) { cur->next = root->right; cur = cur->next; } root = root->next; } else if(cur==root->right) { root = root->next; } else { // cur is the child of the previous node of root if(!root->left && !root->right) { root = root->next; continue; } cur->next = root->left ? root->left : root->right; cur = cur->next; } } connect(leftMost); } }; ```

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35``` ```class Solution { public: void connect(TreeLinkNode *root) { TreeLinkNode *leftMost = root; while(leftMost) { root = leftMost; while(root && !root->left && !root->right) root = root->next; if(!root) return; leftMost = root->left ? root->left : root->right; TreeLinkNode *cur = leftMost; while(root) { if(cur==root->left) { if(root->right) { cur->next = root->right; cur = cur->next; } root = root->next; } else if(cur==root->right) { root = root->next; } else { // cur is the child of the previous node of root if(!root->left && !root->right) { root = root->next; continue; } cur->next = root->left ? root->left : root->right; cur = cur->next; } } } } }; ```

#### 1 comment:

1. 看不太懂第一种解法哇。可以再讲讲么？谢谢了。也不知道你还在不在？