Given the root of a binary tree, flatten the tree into a “linked list”:
– The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
– The “linked list” should be in the same order as a pre-order traversal of the binary tree.
Recursively run through the whole tree. During return of the recursion, root.right is set to left_linked_list (return from left recursion) and the end of left_linked_list.right is set to right_linked_list (return from right recursion). One gotcha, is the need to account for left_linked_list being empty/null. Also, don’t forget to set root.left to null.
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {void} Do not return anything, modify root in-place instead. */ var lastEl = function(root) { let curr = root; while (curr.right !== null) curr = curr.right; return curr; } var flatten = function(root) { if (!root) return null; let leftLL = flatten(root.left); let rightLL = flatten(root.right); root.left = null; //root.right = null; if (leftLL) { root.right = leftLL; lastEl(leftLL).right = rightLL; } else { root.right = rightLL; } return root; }; |