先、中、后序遍历
const tree = {val: 1,left: {val: 2,left: {val: 3,left: null,right: null,},right: {val: 4,left: null,right: null,}},right: {val: 5,left: {val: 6,left: null,right: null,},right: {val: 7,left: null,right: null,}}}// // 根,左,右// const preorder = (root) => {// if(!root) {return }// console.log(root.val);// preorder(root.left);// preorder(root.right);// }// preorder(tree);// 左,根, 右,// const inorder = (root) => {// if(!root) {return }// inorder(root.left);// console.log(root.val);// inorder(root.right);// }// inorder(tree);// 左, 右,根,const postorder = (root) => {if(!root) {return }postorder(root.left);postorder(root.right);console.log(root.val);}postorder(tree);// ========================================== 非递归// 前序 根,左,右// const preorder = (root) => {// if(!root) {return }// const stack = [root];// while(stack.length) {// const n = stack.pop();// console.log(n.val);// // 栈是先进后出,所以我们先把右节点push进去// if(n.right) stack.push(n.right)// if(n.left) stack.push(n.left)// }// }// preorder(tree);// 中序左,根, 右,// const inorder = (root) => {// if(!root) {return }// const stack = [];// let p = root;// while(stack.length || p) {// while(p) {// stack.push(p);// p = p.left// }// const n = stack.pop();// console.log(n.val);// p = n.right// }// }// inorder(tree);// 后序 左, 右,根,const postorder = (root) => {if(!root) {return }const stack = [root];const outPutStack = [];while(stack.length) {const n = stack.pop();outPutStack.push(n)// 栈是先进后出,所以我们先把右节点push进去if(n.left) stack.push(n.left)if(n.right) stack.push(n.right)}while(outPutStack.length) {const n = outPutStack.pop();console.log(n.val);}}postorder(tree);
