重建二叉樹(JS實現)
阿新 • • 發佈:2019-01-01
題目
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
//在此作答
}
思路
二叉樹的前序遍歷第一個節點,即為根節點。找到中序遍歷中根節點的位置,其左邊的序列即為其左子樹,右邊的序列即為右子樹,這樣就把原序列劃分為兩個子序列,分別對兩個子序列進行遞迴操作,就成功地構造了二叉樹
程式碼
function reConstructBinaryTree(pre, vin)
{
if (pre.length === 0) return; //如果前序遍歷為空,說明已經沒有節點了
var root = new TreeNode(pre[0]); //生成根節點
var root_index = vin.indexOf(root.val); //找到根節點在中序遍歷中的位置
root.left = reConstructBinaryTree(pre.slice(1,root_index+1), vin.slice(0,root_index)); //遞迴生成左子樹
root.right = reConstructBinaryTree(pre.slice(root_index+1), vin.slice(root_index+1)); //遞迴生成右子樹
return root;
}