实现二叉树先序,中序和后序遍历
题目描述:分别按照二叉树先序,中序和后序打印所有的节点。
语言:JavaScript
解法:递归
思路:在主函数中定义三个数组,分别用来进行前、中、后序遍历;再定义一个数组用来统一返回前三个数组的结果
依次按照前、中、后的遍历顺序向数组中添加节点
补充:
- 前序遍历:根左右
- 中序遍历:左根右
- 右序遍历:左右根
(前、中、后指根的位置,其他节点的遍历顺序都是从左到右)
function first(root,arr){ //前序遍历 if(root == null) return; //当没有节点元素时,直接返回 arr.push(root.val); //先把根节点添加到arr数组的末端 first(root.left,arr); //递归,依次添加根节点的左边节点,直到根节点无左边节点 first(root.right,arr); //递归,再依次添加第一个根节点的右边节点,直到根节点无右边节点 } function mid(root,arr){ //中序遍历 if(root == null) return; mid(root.left,arr) arr.push(root.val); mid(root.right,arr) } function last(root,arr){ //后序遍历 if(root == null) return; last(root.left,arr); last(root.right,arr); arr.push(root.val) } function threeOrders( root ) { // write code here let arr1 = [],arr2 = [],arr3 = []; let ret = []; first(root,arr1) mid(root,arr2) last(root,arr3) ret.push(arr1) //把前序遍历完的数组arr1添加到ret数组的最末位 ret.push(arr2) ret.push(arr3) return ret } module.exports = { threeOrders : threeOrders };