LeetCode - Convert Binary Search Tree to Sorted Doubly Linked List
阿新 • • 發佈:2018-11-03
解法一:inorder recursion
class Solution { public: Node* treeToDoublyList(Node* root) { if(!root) return nullptr; Node* head=NULL, *pre=NULL; inorder(root, pre, head); pre->right = head; head->left = pre; return head; } void inorder(Node* root, Node*& pre, Node*& head){ if(!root) return; inorder(root->left, pre, head); if(!head) { head = root; pre = root; } else{ pre->right = root; root->left = pre; pre = root; } inorder(root->right, pre, head); } };
解法二:inorder non-recrusion stack
class Solution { public: Node* treeToDoublyList(Node* root) { if(!root) return nullptr; stack<Node*> st; Node* head = NULL, *pre=NULL; while(!st.empty() || root){ while(root){ //left subtreee st.push(root); root=root->left; } root = st.top(); st.pop(); //current node if(!head){ head = root; pre = root; }else{ pre->right = root; root->left = pre; pre = root; } root=root->right; //right } pre->right = head; head->left = pre; return head; } };