二叉树的创建,插入,查找,清空和比较
二叉树的结构
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); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具