题解 | #二叉搜索树与双向链表#
二叉搜索树与双向链表
https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree) {
if(!pRootOfTree) return pRootOfTree;
stack<TreeNode*>st;
stack<TreeNode*>st_tmp;
TreeNode*cur=pRootOfTree;
while(cur||!st.empty()){
while(cur){
st.push(cur);
cur=cur->left;
}
if(!st.empty()){
cur=st.top();
st.pop();
st_tmp.push(cur);
cur=cur->right;
}
}
while(st_tmp.size()>1){
TreeNode*cur1=st_tmp.top();
st_tmp.pop();
TreeNode*cur2=st_tmp.top();
cur1->left=cur2;
cur2->right=cur1;
}
return st_tmp.top();
}
};
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree) {
if(!pRootOfTree) return pRootOfTree;
stack<TreeNode*>st;
stack<TreeNode*>st_tmp;
TreeNode*cur=pRootOfTree;
while(cur||!st.empty()){
while(cur){
st.push(cur);
cur=cur->left;
}
if(!st.empty()){
cur=st.top();
st.pop();
st_tmp.push(cur);
cur=cur->right;
}
}
while(st_tmp.size()>1){
TreeNode*cur1=st_tmp.top();
st_tmp.pop();
TreeNode*cur2=st_tmp.top();
cur1->left=cur2;
cur2->right=cur1;
}
return st_tmp.top();
}
};