題目描述:重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
題目解析
function reConstructBinaryTree(pre, vin) {
//如果先序遍歷和中序遍歷的長度均爲0,那麼返回null
if (pre.length == 0 || vin.length == 0) {
return null;
};
//新建樹,根節點爲先序遍歷的第一個位置的元素
var index = vin.indexOf(pre[0]);
//從中序遍歷拿到根節點的左右子樹
var left = vin.slice(0, index);
var right = vin.slice(index + 1);
//創建新節點
var node = new TreeNode(vin[index]);
//遞歸調用函數,實現新建節點循環
node.left = reConstructBinaryTree(pre.slice(1, index + 1), left);
node.right = reConstructBinaryTree(pre.slice(index + 1), right);
//返回這個節點
return node;
}
測試結果
異想天開,其樂融融!