The data structure TreeNode is used for binary tree, but it can also used to represent a single linked list (where left is null, and right is the next node in the list). Implement a method to convert a binary search tree (implemented with TreeNode) into a single linked list. The values should be kept in order and the operation should be performed in place (that is, on the original data structure).
Return the head node of the linked list after converting.
Note: This problem is slightly different from the original one in the book.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{privateTreeNodeprev;publicTreeNodeconvertBiNode(TreeNoderoot){TreeNodedummy=newTreeNode(0,null,root);prev=dummy;dfs(root);returndummy.right;}privatevoiddfs(TreeNoderoot){if(root==null){return;}dfs(root.left);prev.right=root;root.left=null;prev=root;dfs(root.right);}}
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classSolution{public:TreeNode*prev;TreeNode*convertBiNode(TreeNode*root){TreeNode*dummy=newTreeNode(0,nullptr,root);prev=dummy;dfs(root);returndummy->right;}voiddfs(TreeNode*root){if(!root)return;dfs(root->left);prev->right=root;root->left=nullptr;prev=root;dfs(root->right);}};
1 2 3 4 5 6 7 8 910111213141516171819202122232425
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcconvertBiNode(root*TreeNode)*TreeNode{dummy:=&TreeNode{Val:0,Right:root}prev:=dummyvardfsfunc(root*TreeNode)dfs=func(root*TreeNode){ifroot==nil{return}dfs(root.Left)prev.Right=rootroot.Left=nilprev=rootdfs(root.Right)}dfs(root)returndummy.Right}