题目
思路
本题目要求将一个二叉搜索树转换成顺序单链表。
一个问题:如果我们已经得到了一棵二叉搜索树的左子树和右子树转换得到的结果,如何计算最终结果呢?
4
|
2----+----7
| |
1--+--3 6--+--8
对于根节点4,其左子树计算结果为1,2,3
,右子树计算结果为6,7,8
,我们只要用根节点4将左右子树的结果连接起来即得到最终的结果。为了将左右子树结果和本节点连接起来,需要左子树结果的尾结点和右子树结果的头节点,因此我们需要同时返回头节点和尾结点(通过引用)。
代码
class Solution {
public:
TreeNode* increasingBST(TreeNode* root) {
TreeNode *head, *tail;
link(root, head, tail);
return head;
}
void link(TreeNode* node, TreeNode* &head, TreeNode* &tail) {
if (node == nullptr) {
head = nullptr;
tail = nullptr;
return;
}
TreeNode *h, *t;
link(node->left, h, t);
if (h != nullptr) {
head = h;
t->right = node;
node->left = nullptr;
tail = node;
} else {
head = node;
tail = node;
}
link(node->right, h, t);
tail->right = h;
if (t != nullptr) {
tail = t;
}
}
};