"""# Definition for a Node.class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right"""classSolution:deftreeToDoublyList(self,root:"Node")->"Node":defdfs(root):ifrootisNone:returndfs(root.left)nonlocalhead,preifpre:pre.right=rootelse:head=rootroot.left=prepre=rootdfs(root.right)ifrootisNone:returnNonehead=pre=Nonedfs(root)head.left=prepre.right=headreturnhead
/*// Definition for a Node.class Node { public int val; public Node left; public Node right; public Node() {} public Node(int _val) { val = _val; } public Node(int _val,Node _left,Node _right) { val = _val; left = _left; right = _right; }};*/classSolution{privateNodehead;privateNodepre;publicNodetreeToDoublyList(Noderoot){if(root==null){returnnull;}dfs(root);head.left=pre;pre.right=head;returnhead;}privatevoiddfs(Noderoot){if(root==null){return;}dfs(root.left);if(pre!=null){pre.right=root;}else{head=root;}root.left=pre;pre=root;dfs(root.right);}}
/*// 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; }};*/classSolution{public:Node*treeToDoublyList(Node*root){if(!root){returnnullptr;}Node*pre=nullptr;Node*head=nullptr;function<void(Node*)>dfs=[&](Node*root){if(!root){return;}dfs(root->left);if(pre){pre->right=root;}else{head=root;}root->left=pre;pre=root;dfs(root->right);};dfs(root);head->left=pre;pre->right=head;returnhead;}};
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * } */functreeToDoublyList(root*Node)*Node{ifroot==nil{returnnil}varhead,pre*Nodevardfsfunc(*Node)dfs=func(root*Node){ifroot==nil{return}dfs(root.Left)ifpre!=nil{pre.Right=root}else{head=root}root.Left=prepre=rootdfs(root.Right)}dfs(root)head.Left=prepre.Right=headreturnhead}
/*// Definition for a Node.public class Node { public int val; public Node left; public Node right; public Node() {} public Node(int _val) { val = _val; left = null; right = null; } public Node(int _val,Node _left,Node _right) { val = _val; left = _left; right = _right; }}*/publicclassSolution{privateNodehead;privateNodepre;publicNodeTreeToDoublyList(Noderoot){if(root==null){returnnull;}dfs(root);head.left=pre;pre.right=head;returnhead;}privatevoiddfs(Noderoot){if(root==null){return;}dfs(root.left);if(pre!=null){pre.right=root;}else{head=root;}root.left=pre;pre=root;dfs(root.right);}}