211 lines
8.1 KiB
HTML
211 lines
8.1 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh-Hans">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>047. 从前序与中序遍历序列构造二叉树 – 图解</title>
|
||
<link rel="stylesheet" href="../shared/style.css">
|
||
<style>
|
||
/* page-specific overrides */
|
||
.vis-area { min-height: 120px; padding: 16px 0; }
|
||
.code-section { margin-top: 16px; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="container">
|
||
<h1>🟡 047. 从前序与中序遍历序列构造二叉树 <span class="badge medium">中等</span></h1>
|
||
<p class="subtitle">分类:二叉树 | LeetCode Hot 100</p>
|
||
|
||
<!-- 控制面板 -->
|
||
<div class="controls" id="controls">
|
||
<label for="inputArea">输入:</label>
|
||
<input type="text" id="inputArea" placeholder="默认示例,可自定义">
|
||
<button id="applyBtn" class="primary">生成图解</button>
|
||
<select id="exampleSelect"></select>
|
||
<span style="flex:1"></span>
|
||
<button id="prevBtn">◀ 上一步</button>
|
||
<button id="nextBtn">下一步 ▶</button>
|
||
<button id="jumpBtn">⏭ 跳到结果</button>
|
||
<button id="autoBtn">自动播放</button>
|
||
<button id="resetBtn">重置</button>
|
||
</div>
|
||
|
||
<!-- 步骤流水线 -->
|
||
<div class="pipeline" id="pipeline"></div>
|
||
|
||
<!-- 提示条 -->
|
||
<div class="hint info" id="hintBox">
|
||
<span id="stepInfo"></span><br>
|
||
<span id="hintText"></span>
|
||
</div>
|
||
|
||
<!-- 可视化面板 -->
|
||
<div class="panels">
|
||
<div class="panel" id="mainPanel">
|
||
<h3>📊 可视化</h3>
|
||
<div class="vis-area" id="vizArea">点击「生成图解」开始</div>
|
||
</div>
|
||
<div class="panel-grid">
|
||
<div class="panel" id="detailPanel">
|
||
<h3>📝 当前步骤详情</h3>
|
||
<div id="detailContent">等待开始...</div>
|
||
</div>
|
||
<div class="panel" id="resultPanel">
|
||
<h3>✅ 结果</h3>
|
||
<div id="resultContent">等待完成...</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 代码 -->
|
||
<div class="panel code-section">
|
||
<h3>💻 参考代码(Python)</h3>
|
||
<div id="codeArea"></div>
|
||
</div>
|
||
|
||
<footer>Powered by QwenPaw · 图解算法 · LeetCode Hot 100</footer>
|
||
</div>
|
||
|
||
<script src="../shared/algo-viz.js"></script>
|
||
<script>
|
||
"use strict";
|
||
(function() {
|
||
// ========== Algorithm Logic ==========
|
||
|
||
function arrayToTree(arr) {
|
||
if (!arr || arr.length === 0) return null;
|
||
let idCtr = 0;
|
||
const nodes = arr.map(v => v === null ? null : {val: v, left: null, right: null, _id: 'n' + (idCtr++)});
|
||
for (let i = 0; i < nodes.length; i++) {
|
||
if (!nodes[i]) continue;
|
||
const li = 2*i+1, ri = 2*i+2;
|
||
if (li < nodes.length) nodes[i].left = nodes[li];
|
||
if (ri < nodes.length) nodes[i].right = nodes[ri];
|
||
}
|
||
return nodes[0];
|
||
}
|
||
function treeToArray(root) {
|
||
if (!root) return [];
|
||
const res = [], q = [root];
|
||
while (q.length) {
|
||
const n = q.shift();
|
||
if (n === null) { res.push(null); continue; }
|
||
res.push(n.val); q.push(n.left, n.right);
|
||
}
|
||
while (res.length && res[res.length-1] === null) res.pop();
|
||
return res;
|
||
}
|
||
function deepClone(node) {
|
||
if (!node) return null;
|
||
return {val: node.val, _id: node._id, left: deepClone(node.left), right: deepClone(node.right)};
|
||
}
|
||
|
||
const examples = [
|
||
{preorder: [3,9,20,15,7], inorder: [9,3,15,20,7], label: '示例1: pre=[3,9,20,15,7] in=[9,3,15,20,7]'},
|
||
{preorder: [-1], inorder: [-1], label: '示例2: 单节点'},
|
||
];
|
||
let preo, ino, steps, stepCtrl, builtRoot;
|
||
let idCtr;
|
||
|
||
function buildSteps(pre, ine) {
|
||
preo = [...pre]; ino = [...ine];
|
||
steps = []; idCtr = 0;
|
||
const inMap = {};
|
||
ine.forEach((v,i) => inMap[v] = i);
|
||
|
||
steps.push({stage:'init', hlPre:{}, hlIn:{}, msg:'前序找根,中序分左右,递归构造'});
|
||
|
||
function build(pl, pr, il, ir) {
|
||
if (pl > pr) return null;
|
||
const rootVal = pre[pl];
|
||
const node = {val: rootVal, _id: 'n' + (idCtr++), left: null, right: null};
|
||
const inIdx = inMap[rootVal];
|
||
const leftSize = inIdx - il;
|
||
const hlPre = {}, hlIn = {};
|
||
hlPre[pl] = 'orange';
|
||
for (let i = pl+1; i <= pr; i++) hlPre[i] = 'default';
|
||
for (let i = il; i <= ir; i++) hlIn[i] = i === inIdx ? 'orange' : (i < inIdx ? 'blue' : 'purple');
|
||
|
||
steps.push({stage:'select', hlPre, hlIn, msg:`根 = pre[${pl}]=${rootVal},中序位置=${inIdx},左子树 ${leftSize} 个,右子树 ${pr-pl-leftSize} 个`, rootVal, inIdx});
|
||
node.left = build(pl + 1, pl + leftSize, il, inIdx - 1);
|
||
node.right = build(pl + leftSize + 1, pr, inIdx + 1, ir);
|
||
return node;
|
||
}
|
||
builtRoot = build(0, pre.length - 1, 0, ine.length - 1);
|
||
steps.push({stage:'done', hlPre:{}, hlIn:{}, msg:'构造完成!'});
|
||
}
|
||
|
||
function render(step) {
|
||
const s = steps[step];
|
||
let viz = '<div><b>前序:</b></div>';
|
||
viz += renderArray(preo, {highlights: s.hlPre || {}});
|
||
viz += '<div style="margin-top:6px;"><b>中序:</b></div>';
|
||
viz += renderArray(ino, {highlights: s.hlIn || {}});
|
||
if (s.inIdx !== undefined) {
|
||
viz += `<div class="partition-legend" style="margin-top:6px;">
|
||
<span><span class="dot-lg" style="background:var(--blue-light);"></span> 左子树</span>
|
||
<span><span class="dot-lg" style="background:var(--orange-light);"></span> 根</span>
|
||
<span><span class="dot-lg" style="background:var(--purple-light);"></span> 右子树</span>
|
||
</div>`;
|
||
}
|
||
if (builtRoot) {
|
||
viz += '<div style="margin-top:10px;"><b>构造中的树:</b></div>';
|
||
viz += renderBinaryTree(builtRoot, {highlights: {}});
|
||
}
|
||
$('vizArea').innerHTML = viz;
|
||
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
|
||
if (s.stage === 'done') {
|
||
$('resultContent').innerHTML = `<div class="final-answer">构造的树 = <b>[${treeToArray(builtRoot)}]</b></div>`;
|
||
}
|
||
$('hintText').textContent = s.msg;
|
||
const stages = ['init→初始化','select→选根','done→完成'];
|
||
$('pipeline').innerHTML = stages.map(st => {
|
||
const [k,l] = st.split('→');
|
||
return `<span class="pipe-step ${s.stage===k?'active':''}">${l}</span>`;
|
||
}).join('<i>→</i>');
|
||
}
|
||
|
||
function init() {
|
||
const sel = $('exampleSelect');
|
||
examples.forEach((e,i) => { sel.innerHTML += `<option value="${i}">${e.label}</option>`; });
|
||
$('inputArea').value = 'pre=[3,9,20,15,7] in=[9,3,15,20,7]';
|
||
buildSteps(examples[0].preorder, examples[0].inorder);
|
||
stepCtrl = new StepController({onStep: render});
|
||
stepCtrl.setSteps(steps.map((_,i)=>i));
|
||
$('stepInfo').textContent = '步骤 1 / ' + steps.length;
|
||
stepCtrl.onStep = (idx) => { render(idx); $('stepInfo').textContent = `步骤 ${idx+1} / ${steps.length}`; };
|
||
$('applyBtn').onclick = () => {
|
||
const m = $('inputArea').value.match(/pre=\[([^\]]+)\].*in=\[([^\]]+)\]/);
|
||
if (!m) { alert('格式: pre=[3,9,20,15,7] in=[9,3,15,20,7]'); return; }
|
||
const pre = JSON.parse('['+m[1]+']'), ine = JSON.parse('['+m[2]+']');
|
||
buildSteps(pre, ine); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length;
|
||
};
|
||
$('exampleSelect').onchange = () => {
|
||
const e = examples[parseInt($('exampleSelect').value)];
|
||
$('inputArea').value = `pre=[${e.preorder}] in=[${e.inorder}]`;
|
||
buildSteps(e.preorder, e.inorder); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0);
|
||
};
|
||
$('prevBtn').onclick = () => stepCtrl.prev();
|
||
$('nextBtn').onclick = () => stepCtrl.next();
|
||
$('jumpBtn').onclick = () => stepCtrl.jumpToEnd();
|
||
$('autoBtn').onclick = () => { const on = stepCtrl.toggleAuto(); $('autoBtn').textContent = on ? '暂停' : '自动播放'; };
|
||
$('resetBtn').onclick = () => { stepCtrl.reset(); $('autoBtn').textContent = '自动播放'; };
|
||
}
|
||
init();
|
||
$('codeArea').innerHTML = renderCode(`def buildTree(preorder, inorder):
|
||
in_map = {v: i for i, v in enumerate(inorder)}
|
||
def build(pl, pr, il, ir):
|
||
if pl > pr: return None
|
||
root_val = preorder[pl]
|
||
idx = in_map[root_val]
|
||
left_size = idx - il
|
||
root = TreeNode(root_val)
|
||
root.left = build(pl+1, pl+left_size, il, idx-1)
|
||
root.right = build(pl+left_size+1, pr, idx+1, ir)
|
||
return root
|
||
return build(0, len(preorder)-1, 0, len(inorder)-1)`, {lang:'Python'});
|
||
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html> |