标签:排序 oid leetcode public 不能 head tree 循环 off
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
class Solution {
public:
Node* treeToDoublyList(Node* root) {
if (!root) return NULL;
recur(root);
head->left = pre;
pre->right = head;
return head;
}
private:
Node *head = NULL, *pre = NULL;
void recur(Node* root) {
if (!root) return;
recur(root->left);
// ------ 中序操作
root->left = pre;
if (pre) pre->right = root;
else head = root;
pre = root;
// ------
recur(root->right);
}
};
只要能想到使用一个全局节点pre
来表示上一个节点,这道题就迎刃而解了。需要注意的是,声明指针时一定要初始化(被折磨,说多了都是泪)。
class Solution {
public:
Node* treeToDoublyList(Node* root) {
if (!root) return NULL;
Node *head = NULL, *pre = NULL, *cur = root;
stack<Node*> s;
while (!s.empty() || cur) {
while (cur) {
s.push(cur);
cur = cur->left;
}
cur = s.top(); s.pop();
// ------ 中序操作
if (pre) pre->right = cur;
else head = cur;
cur->left = pre;
pre = cur;
// ------
cur = cur->right;
}
head->left = pre;
pre->right = head;
return head;
}
};
标签:排序 oid leetcode public 不能 head tree 循环 off
原文地址:https://www.cnblogs.com/tmpUser/p/14459769.html