2024每日刷题(148)
Leetcode—426. 将二叉搜索树转化为排序的双向链表
实现代码
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node() {}
Node(int _val) {
val = _val;
left = NULL;
right = NULL;
}
Node(int _val, Node* _left, Node* _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
public:
Node* treeToDoublyList(Node* root) {
if(root == nullptr) {
return (Node*)nullptr;
}
// 中序遍历
stack<Node*> st;
Node* first = nullptr;
Node* pre = nullptr;
while(root != nullptr || !st.empty()) {
// 左子树全部入栈
while(root != nullptr) {
st.push(root);
root = root->left;
}
root = st.top(), st.pop();
if(first == nullptr) {
first = root;
}
if(pre != nullptr) {
pre->right = root;
root->left = pre;
}
pre = root;
root = root->right;
}
first->left = pre;
pre->right = first;
return first;
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!