[LeetCode] 117. Populating Next Right Pointers in Each Node II, leetcodepointers
[Question]
Follow up for problem "Populating Next Right Pointers in Each Node ".
What if the given tree cocould be any binary tree? Wocould 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 shoshould look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
[Analysis]
None
[Code]
/********************************** Date: * Author: SJF0115 * Subject: 117. populating Next Right Pointers in Each Node II * Source: Pull result: AC * Source: LeetCode * conclusion: * *********************************/# include <iostream> # include <queue> using namespace std; struct TreeLinkNode {int val; TreeLinkNode * left; TreeLinkNode * right; TreeLinkNode * Next; TreeLinkNode (int x): val (x), left (NULL), right (NULL), next (NULL) {}}; class Solution {public: void connect (TreeLinkNode * root) {if (root = NULL) {return;} // if queue <TreeLinkNode *> cur; queue <TreeLinkNode *> next; cur. push (root); TreeLinkNode * p, * pre; while (! Cur. empty () {pre = NULL; // The current layer traverses while (! Cur. empty () {// out queue p = cur. front (); cur. pop (); // horizontally connected if (pre! = NULL) {pre-> next = p;} // if pre = p; // next stores the next layer of nodes. // The left subtree is not empty and is added to the queue. if (p-> left) {next. push (p-> left);} // if // Add the right subtree to the queue if (p-> right) {next. push (p-> right) ;}// if} // while p-> next = NULL; swap (next, cur) ;}// while }}; // create a binary tree int CreateBTree (TreeLinkNode * & T) {int data; // input the value of the node in the binary tree in the first order, -1 indicates the empty tree cin> data; if (data =-1) {T = NULL;} else {T = new TreeLinkNode (data ); // construct the left subtree CreateBTree (T-> left); // construct the right subtree CreateBTree (T-> right);} return 0 ;} // output void LevelOrder (TreeLinkNode * root) {if (root = NULL) {return;} // if TreeLinkNode * p = root, * q; while (p) {q = p; // horizontal output while (q) {cout <q-> val <"->"; q = q-> next ;} // while if (q = NULL) {cout <"NULL" <endl;} // if p = p-> left ;} // while} int main () {Solution solution; TreeLinkNode * root (0); CreateBTree (root); solution. connect (root); LevelOrder (root );}