二叉樹的結構
function TreeNode(){ this.val = val; this.left = null; this.right = null; }
二叉樹的建立
function createBTree(aVal,fPredicate,pos){ var node = {}; pos = pos || 0; if(fPredicate(aVal,pos) || !aVal[pos]){ return null; } else{ node.val = aVal[pos]; node.left = createBTree(aVal,fPredicate,2*pos+1); node.right = createBTree(aVal,fPredicate,2*pos+2); } return node; }
二叉樹的插入節點
function BTreeInsert(root,val,direction,node){ if(root == null){ return false; } if(root.val === val){ switch(direction){ case 'left': if(root.left){ //throw new Error('left node already exists'); return false; } else{ root.left = node; } break; case 'right': if(root.right){ //throw new Error('right node already exists'); return false; } else{ root.right = node; } break; } } else{ BTreeInsert(root.left,node,val,direction); BTreeInsert(root.right,node,val,direction); } return true; }
二叉樹的查詢節點
function DLRFind(root, val) { if (root == null) { return null; } if (root.val === val) { return root; } return DLRFind(root.left, val) || DLRFind(root.right, val); }
二叉樹的比較
function BTreeCompare(root1,root2){ if(root1 == null && root2 == null){ return true; } else if(root1 != null && root2 != null){ return BTreeCompare(root1.left,root2.left) && BTreeCompare(root1.right,root2.right); } else{ return false; } }
清空二叉樹
function BTreeClear(root){ if(root == null){ return true; } BTreeClear(root.left); BTreeClear(root.right); root = null; return true; }
測試程式碼
var root = createBTree([3, 2, 4, 6, 7, 8, 1, 0], function (aVal, pos) { return aVal[pos] == 0 || pos > 8 }, 0); DLR(root);//output 3 2 6 7 4 8 1 DLRFind(root,2);//output node 2 DLRFind(root,11);//output null function createBTree(aVal, fPredicate, pos) { var node = {}; pos = pos || 0; if (fPredicate(aVal, pos) || !aVal[pos]) { return null; } else { node.val = aVal[pos]; node.left = createBTree(aVal, fPredicate, 2 * pos + 1); node.right = createBTree(aVal, fPredicate, 2 * pos + 2); } return node; } function DLR(root) { if (root == null) { return null; } else { console.log('d ' + root.val); DLR(root.left); DLR(root.right); } } function DLRFind(root, val) { if (root == null) { return null; } if (root.val === val) { return root; } return DLRFind(root.left, val) || DLRFind(root.right, val); }