二叉树的先中后序遍历-JS递归实现
1 const bt = { 2 val: 1, 3 left: { 4 val: 2, 5 left: { 6 val: 4, 7 left: null, 8 right: null, 9 }, 10 right: { 11 val: 5, 12 left: null, 13 right: null, 14 }, 15 }, 16 right: { 17 val: 3, 18 left: { 19 val: 6, 20 left: null, 21 right: null, 22 }, 23 right: { 24 val: 7, 25 left: null, 26 right: null, 27 }, 28 }, 29 }; 30 //先序遍历 31 const preorder = (root) => { 32 if(!root) {return;} 33 console.log(root.val); 34 preorder(root.left); 35 preorder(root.right); 36 }; 37 38 preorder(bt); 39 40 //中序遍历 41 const inorder = (root) => { 42 if(!root) {return;} 43 inorder(root.left); 44 console.log(root.val); 45 inorder(root.right); 46 }; 47 inorder(bt); 48 49 //后序遍历 50 const postorder = (root) => { 51 if(!root) {return;} 52 postorder(root.left); 53 postorder(root.right); 54 console.log(root.val); 55 }; 56 57 postorder(bt);
本文作者:oaoa
本文链接:https://www.cnblogs.com/oaoa/p/14842243.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步