輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的雙向鏈表。要求不能建立任何新的結點,只能調整樹中結點指針的指向。算法
若是是這樣一棵二叉搜索樹:this
那麼它對應的雙向鏈表順序爲:spa
1 3 4 5 7 10 11 15
仔細觀察發現這個序列和樹的中序遍歷是同樣的,因此算法就好寫了,先中序遍歷獲得一個序列,而後再按照雙向鏈表的指針規則連接起來便可。指針
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function Convert(r) { if(r === null) return r; var q = [], s = []; var cur = r; while(cur !== null || s.length !== 0) { if(cur !== null){ s.push(cur); cur = cur.left; }else{ cur = s.pop(); q.push(cur); cur = cur.right; } } r = q.shift(); r.left = null; r.right = null; var tail = r; cur = null; while(q.length !== 0){ cur = q.shift(); tail.right = cur; cur.left = tail; tail = cur; } return r; }