二叉搜索樹與雙向鏈表
題目描述
輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的雙向鏈表。要求不能創(chuàng)建任何新的結點,只能調整樹中結點指針的指向。
思路
- 遞歸思想:把大問題轉換為若干小問題;
- 由于JavaScript中并沒有鏈表或者Tree這樣的原生數(shù)據(jù)結構,都是通過對象模擬的,因此最終要返回的是指向雙向鏈表首結點的指針;
- 將左子樹構成雙向鏈表,返回的是左子樹的尾結點,將其連接到root的左邊;
- 將右子樹構成雙向鏈表,將其追加到root結點之后,并返回尾結點;
- 向左遍歷返回的鏈表至頭結點處,即為所求雙向鏈表的首結點。
實現(xiàn)代碼
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function Convert(pRootOfTree) {
if (!pRootOfTree) {
return null;
}
var lastNode = null;
lastNode = ConvertNode(pRootOfTree, lastNode);
var head = lastNode;
while (head && head.left) {
head = head.left;
}
return head;
}
function ConvertNode(node, lastNode) {
if (!node) {
return;
}
if (node.left) {
lastNode = ConvertNode(node.left, lastNode);
}
node.left = lastNode;
if (lastNode) {
lastNode.right = node;
}
lastNode = node;
if (node.right) {
lastNode = ConvertNode(node.right, lastNode);
}
return lastNode;
}