"""# 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:'Optional[Node]')->'Optional[Node]':defdfs(root):ifrootisNone:returnnonlocalprev,headdfs(root.left)ifprev:prev.right=rootroot.left=prevelse:head=rootprev=rootdfs(root.right)ifrootisNone:returnNonehead=prev=Nonedfs(root)prev.right=headhead.left=prevreturnhead
/*// 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{privateNodeprev;privateNodehead;publicNodetreeToDoublyList(Noderoot){if(root==null){returnnull;}prev=null;head=null;dfs(root);prev.right=head;head.left=prev;returnhead;}privatevoiddfs(Noderoot){if(root==null){return;}dfs(root.left);if(prev!=null){prev.right=root;root.left=prev;}else{head=root;}prev=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*prev;Node*head;Node*treeToDoublyList(Node*root){if(!root)returnnullptr;prev=nullptr;head=nullptr;dfs(root);prev->right=head;head->left=prev;returnhead;}voiddfs(Node*root){if(!root)return;dfs(root->left);if(prev){prev->right=root;root->left=prev;}elsehead=root;prev=root;dfs(root->right);}};
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * } */functreeToDoublyList(root*Node)*Node{ifroot==nil{returnroot}varprev,head*Nodevardfsfunc(root*Node)dfs=func(root*Node){ifroot==nil{return}dfs(root.Left)ifprev!=nil{prev.Right=rootroot.Left=prev}else{head=root}prev=rootdfs(root.Right)}dfs(root)prev.Right=headhead.Left=prevreturnhead}