Populating Next Right Pointers in Each Node IIOct 28 '12
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,
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 * struct TreeLinkNode { * int val; * TreeLinkNode *left; * TreeLinkNode *right; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { if(!root) return; queue<TreeLinkNode *> levelQ; int queueCount=1, levelCount=0; TreeLinkNode *prev=NULL; levelQ.push(root); while (!levelQ.empty()) { while(queueCount) { TreeLinkNode *temp = levelQ.front(); levelQ.pop(); queueCount--; if (prev) prev->next = temp; prev = temp; if (temp->left) { levelQ.push(temp->left); levelCount++; } if (temp->right) { levelQ.push(temp->right); levelCount++; } } queueCount = levelCount++; prev = NULL; levelCount=0; } } };
No comments:
Post a Comment