Files
illustrated-algorithm/lowest-common-ancestor-of-a-binary-tree/index.html
T
2026-08-24 04:35:13 +00:00

212 lines
8.0 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>049. 二叉树的最近公共祖先 – 图解</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>🟡 049. 二叉树的最近公共祖先 <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 = [
{tree: [3,5,1,6,2,0,8,null,null,7,4], p: 5, q: 1, label: '示例1: p=5, q=1 → LCA=3'},
{tree: [3,5,1,6,2,0,8,null,null,7,4], p: 5, q: 4, label: '示例2: p=5, q=4 → LCA=5'},
];
let root, steps, stepCtrl, pVal, qVal, lcaVal;
function findNodeByVal(node, val) {
if (!node) return null;
if (node.val === val) return node;
return findNodeByVal(node.left, val) || findNodeByVal(node.right, val);
}
function buildSteps(arr, p, q) {
root = arrayToTree(arr); pVal = p; qVal = q;
steps = []; lcaVal = null;
const pNode = findNodeByVal(root, p);
const qNode = findNodeByVal(root, q);
const targetHl = {};
if (pNode) targetHl[pNode._id] = 'active';
if (qNode) targetHl[qNode._id] = 'active';
steps.push({stage:'init', hl:Object.assign({}, targetHl), msg:`寻找 ${p} 和 ${q} 的最近公共祖先`});
function dfs(node) {
if (!node) return null;
steps.push({stage:'enter', hl:Object.assign({[node._id]:'current'}, targetHl), msg:`进入节点 ${node.val}`});
if (node.val === p || node.val === q) {
steps.push({stage:'found', hl:{[node._id]:'current'}, msg:`节点 ${node.val} 是目标节点 ${node.val===pVal?'p':'q'}!`});
return node;
}
const left = dfs(node.left);
const right = dfs(node.right);
if (left && right) {
lcaVal = node.val;
steps.push({stage:'lca', hl:{[node._id]:'current'}, msg:`左右子树各找到一个目标,LCA = ${node.val}`, lca:node.val});
return node;
}
const ret = left || right;
if (ret) {
steps.push({stage:'return_one', hl:{[node._id]:'visited'}, msg:`节点 ${node.val}:一侧找到目标,向上返回`});
} else {
steps.push({stage:'return_none', hl:{[node._id]:'visited'}, msg:`节点 ${node.val}:两侧都没找到,返回 null`});
}
return ret;
}
dfs(root);
steps.push({stage:'done', hl:{}, msg:`最近公共祖先 = ${lcaVal !== null ? lcaVal : 'null'}`, lca:lcaVal});
}
function render(step) {
const s = steps[step];
let viz = renderBinaryTree(root, {highlights: s.hl});
viz += `<div style="margin-top:8px;font-size:14px;">p = <b style="color:var(--blue);">${pVal}</b> q = <b style="color:var(--purple);">${qVal}</b></div>`;
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
if (s.stage === 'done') {
$('resultContent').innerHTML = `<div class="final-answer">LCA(${pVal}, ${qVal}) = <b>${s.lca}</b></div>`;
}
$('hintText').textContent = s.msg;
const stages = ['init→初始化','enter→进入','found→找到目标','lca→确定LCA','return_one→返回一侧','return_none→返回空','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 = '[3,5,1,6,2,0,8,null,null,7,4], p=5, q=1';
buildSteps(examples[0].tree, examples[0].p, examples[0].q);
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(/\[([^\]]+)\].*p\s*=\s*(-?\d+).*q\s*=\s*(-?\d+)/);
if (!m) { alert('格式: [3,5,1,...], p=5, q=1'); return; }
const arr = JSON.parse('['+m[1]+']');
buildSteps(arr, parseInt(m[2]), parseInt(m[3]));
stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length;
};
$('exampleSelect').onchange = () => {
const e = examples[parseInt($('exampleSelect').value)];
$('inputArea').value = JSON.stringify(e.tree) + `, p=${e.p}, q=${e.q}`;
buildSteps(e.tree, e.p, e.q); 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 lowestCommonAncestor(root, p, q):
if not root or root == p or root == q:
return root
left = lowestCommonAncestor(root.left, p, q)
right = lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left if left else right`, {lang:'Python'});
})();
</script>
</body>
</html>