Advertisement
Guest User

Untitled

a guest
Jun 19th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. /**
  2. * Definition for binary tree with next pointer.
  3. * struct TreeLinkNode {
  4. * int val;
  5. * TreeLinkNode *left, *right, *next;
  6. * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. void connect(TreeLinkNode *root) {
  12. if (root == NULL) return;
  13. TreeLinkNode* p = root->next;
  14. while(p != NULL) {
  15. if (p->left != NULL) {
  16. p = p->left;
  17. break;
  18. }
  19. if (p->right != NULL) {
  20. p = p->right;
  21. break;
  22. }
  23. p = p->next;
  24. }
  25. if (root->right != NULL) {
  26. root->right->next = p;
  27. }
  28. if (root->left != NULL) {
  29. root->left->next = root->right ? root->right : p;
  30. }
  31. connect(root->right);
  32. connect(root->left);
  33. }
  34. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement