二叉 DOM 樹的遍曆
[javascript] view plain copy function Tree() { var Node = function(key){ this.key = key; this.left = null; this.right = null; } root =null; }
前序走訪
<code style="font-family: 'Source Code Pro', Consolas, Menlo, Monaco, 'Courier New', monospace; font-size: 1em; color: inherit; padding: 0px; white-space: inherit; background: none;">首先訪問根結點,然後遍曆左子樹,最後遍曆右子樹</code>
[javascript] view plain copy Tree.prototype.preOrderTraverse = function(callback){ preOrder(root, callback); } var preOrder = function(node,callback){ if(node !== null){ callback(node.key); preOrder(node.left, callback); preOrder(node.right, callback); } }
<code style="font-family: 'Source Code Pro', Consolas, Menlo, Monaco, 'Courier New', monospace; font-size: 1em; color: inherit; padding: 0px; white-space: inherit; background: none;">修改為DOM二叉樹:</code>
[javascript] view plain copy var preOrder = function(node,callback) { callback(node); if(node.firstElementChild) {//先判斷子項目節點是否存在 this.preOrder(node.firstElementChild,callback); } if(node.lastElementChild) { this.preOrder(node.lastElementChild,callback); } };
中序遍曆
<code style="font-family: 'Source Code Pro', Consolas, Menlo, Monaco, 'Courier New', monospace; font-size: 1em; color: inherit; padding: 0px; white-space: inherit; background: none;">首先遍曆左子樹,然後訪問根結點,最後遍曆右子樹。</code>
[javascript] view plain copy Tree.prototype.inOrderTraverse = function(callback){ inOrder(root, callback); } var inOrder = function(node,callback){ if(node !== null){