struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL
.
Initially, all next pointers are set to NULL
.
Note:
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:
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 connect(TreeLinkNode *root) { if (root == nullptr) return; queue<pair<TreeLinkNode*, int>> traverse; traverse.push(make_pair(root, 0)); while(!traverse.empty()) { auto data = traverse.front(); traverse.pop(); if (data.first->left != nullptr) traverse.push(make_pair(data.first->left, data.second + 1)); if (data.first->right != nullptr) traverse.push(make_pair(data.first->right, data.second + 1)); if (traverse.empty() || traverse.front().second != data.second) data.first->next = nullptr; else data.first->next = traverse.front().first; } } };思路:
刚才没有考虑到空间复杂度要求是O(1)。其实对搜索不可避免用到递归等手法,这样栈的空间复杂度就是O(log N),N为树深。要利用next指针获得相邻树的最左元素。第二题的思路也是类似,只不过要通过next指针找到下一个有子结点的同层结点,这样的话就必须首先保证树的右边部分的next指针有效。
题解:
/** * 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 connect(TreeLinkNode *root) { if (root == nullptr) return; if (root->left != nullptr) root->left->next = root->right; if (root->right != nullptr && root->next != nullptr) root->right->next = root->next->left; else if (root->right != nullptr) root->right->next = nullptr; connect(root->left); connect(root->right); } };
/** * 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 connect(TreeLinkNode* node) { if (node == nullptr) return; if (node->left && node->right) node->left->next = node->right; TreeLinkNode* child = node->left; if (node->right) child = node->right; if (child != nullptr) { TreeLinkNode* i = node->next; while( i != nullptr && i->left == nullptr && i->right == nullptr) i = i->next; if (i != nullptr) { if (i->left) child->next = i->left; else child->next = i->right; } } // This is critical since we need the right hand side // next is ready before the left hand side if (node->right) connect(node->right); if (node->left) connect(node->left); } };