classSolution{public:Node*treeToDoublyList(Node*root){if(root==nullptr)returnnullptr;Node*leftHead=treeToDoublyList(root->left);Node*rightHead=treeToDoublyList(root->right);root->left=root;root->right=root;returnconnect(connect(leftHead,root),rightHead);}private:Node*connect(Node*node1,Node*node2){if(node1==nullptr)returnnode2;if(node2==nullptr)returnnode1;Node*tail1=node1->left;Node*tail2=node2->left;// Connect node1's tail with node2tail1->right=node2;node2->left=tail1;// Connect node2's tail with node1tail2->right=node1;node1->left=tail2;returnnode1;}};
classSolution{publicNodetreeToDoublyList(Noderoot){if(root==null)returnnull;NodeleftHead=treeToDoublyList(root.left);NoderightHead=treeToDoublyList(root.right);root.left=root;root.right=root;returnconnect(connect(leftHead,root),rightHead);}privateNodeconnect(Nodenode1,Nodenode2){if(node1==null)returnnode2;if(node2==null)returnnode1;Nodetail1=node1.left;Nodetail2=node2.left;// Connect node1's tail with node2tail1.right=node2;node2.left=tail1;// Connect node2's tail with node1tail2.right=node1;node1.left=tail2;returnnode1;}}
classSolution{public:// Very simliar to 94. Binary Tree Inorder TraversalNode*treeToDoublyList(Node*root){if(root==nullptr)returnnullptr;stack<Node*>stack;Node*first=nullptr;Node*pred=nullptr;while(root||!stack.empty()){while(root){stack.push(root);root=root->left;}root=stack.top(),stack.pop();if(first==nullptr)first=root;if(pred!=nullptr){pred->right=root;root->left=pred;}pred=root;root=root->right;}pred->right=first;first->left=pred;returnfirst;}};