leetcode

来源:互联网 发布:单片机频率计 编辑:程序博客网 时间:2024/06/07 15:55

题目描述


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
struct TreeLinkNode { *  int val; *  TreeLinkNode *left, *right, *next; *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */class Solution {public:void connect(TreeLinkNode *root) {if (!root)return;queue<TreeLinkNode* > queue;TreeLinkNode* tail = root;TreeLinkNode* temp = nullptr;queue.push(root);while (!queue.empty()){temp = queue.front();queue.pop();if (temp->left){queue.push(temp->left);}if (temp->right){queue.push(temp->right);}if (tail == temp){temp->next = nullptr;tail = queue.back();}else{temp->next = queue.front();}}}};


原创粉丝点击