Binary search tree and double linked list
Input a binary search tree, and transform the binary search tree into a sorted bidirectional linked list. It is required that no new node can be created, only the node pointer in the tree can be adjusted.
thinking
Solution 1: basic recursion
1. Construct the left subtree as a two-way linked list and return to the left node of the chain header
2. Locate the last node of the left bidirectional list
3. The last node and the current node of the left bidirectional link list
4. Construct the right subtree as a two-way linked list and return to the link header node right
5. Connect the header node of the right bidirectional chain with the current node
Solution two:
Use the global variable leftLast to represent the last node of the left bidirectional linked list (that is, tmp in the previous solution)
Code
function Permutation(str) { var result = []; if (str.length <= 0) { return []; } var sortTemp= ""; var arr = str.split(""); result = sortString(arr, sortTemp, []); return result; } function sortString(arr, sortTemp, res) { if (arr.length == 0) { res.push(sortTemp); } else { var isRepeat = {}; for (var i = 0; i < arr.length; i++) { if (!isRepeat[arr[i]]) { var temp = arr.splice(i, 1)[0]; // Take out the i th character sortTemp+= temp; // Prefix the ith character sortString(arr, sortTemp, res); arr.splice(i, 0, temp); // Complete the extracted element and restore the original string sortTmp= sortTemp.slice(0, sortTemp.length - 1); // Clear sortTemp isRepeat[temp] = tru; } } } return res; } //Second kinds /* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ var leftLast; function Convert(root) { // write code here if(!root){ return null; } //Returns the leftmost header node, and the last node of the left bidirectional list is the same node if(root == null && root == null){ leftLast = root; return root; } //Construct the left subtree as a two-way linked list and return to the left node of the chain header var left = Convert(root.left); //If the left subtree exists, connect the last node of the left bidirectional list with the current node //Here, the existence of leftLast and left is not exactly the same! if(left){ leftLast.right = root; root.left = leftLast; } //At this time, whether there is left or not, the last node of the left bidirectional list is the current root leftLast = root; //Construct the right subtree as a two-way linked list and return to the link header node right var right = Convert(root.right); //Connect the header node of the right bidirectional chain with the current node if(right){ right.left = root; root.right = right; } //If there is a left subtree, it always returns the leftmost leaf node (that is, the smallest node). If there is no left subtree, the root node is the smallest node. return left?left:root; }