From ff610c9e0cf481305cac574bd89c015559c953e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=8Fgnacio?= Date: Sun, 26 Feb 2017 22:55:24 -0300 Subject: [PATCH] another recursive solution --- 114 Flatten Binary Tree to Linked List.js | 29 ++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/114 Flatten Binary Tree to Linked List.js b/114 Flatten Binary Tree to Linked List.js index 2f68381..1b20145 100644 --- a/114 Flatten Binary Tree to Linked List.js +++ b/114 Flatten Binary Tree to Linked List.js @@ -16,12 +16,12 @@ var flatten = function(root) { var stack = []; var p = root; - + while(p !== null || stack.length !== 0){ if(p.right !== null){ stack.push(p.right); } - + if(p.left !== null){ // [!!!]point of confusing, if null then pop stack p.right = p.left; p.left = null; @@ -29,8 +29,31 @@ var flatten = function(root) { var node = stack.pop(); p.right = node; } - + p = p.right; } }; +// Recursive solution + +var flatten = function(root) { + if(root === null || (root.left === null && root.right === null)) { + return; + } + + var rootLeft = root.left; + var rootRight = root.right; + root.left = null; + root.right = null; + + flatten(rootLeft); + flatten(rootRight); + + root.right = rootLeft; + + var aux = root; + while(aux !== null && aux.right !== null) { + aux = aux.right; + } + aux.right = rootRight; +};