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
解题思路:每层的元素可以看成一个链表,可以使用递归完成,每层整体又可以看成一个递归来解决。
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void listRecursion(TreeLinkNode *root, TreeLinkNode* &lastNode){ if(NULL == root) return; listRecursion(root->next, lastNode); if(root->right){ root->right->next = lastNode; lastNode = root->right; } if(root->left){ root->left->next = lastNode; lastNode = root->left; } } void treeRecursion(TreeLinkNode *root){ if(NULL == root) return; TreeLinkNode* lastNode = NULL; listRecursion(root, lastNode); treeRecursion(lastNode); } void connect(TreeLinkNode *root) { treeRecursion(root); } };