利用栈实现二叉树的前序、中序、后序遍历
/**
* 注意:left/right值若没有显示设置为null,值即为undefined
* 在调用二叉树前、中、后序遍历方法时,由于参数设置了默认值(tree)
* 所以进入了死循环
*/
const tree = { value: 5, left: { value: 3, left: { value: 2, left: null, right: null }, right: { value: 4, left: null, right: null } }, right: { value: 7, left: { value: 6, left: null, right: null }, right: { value: 8, left: null, right: null } } }
/**
* 前序遍历
* root -> left -> right
*/
const preOrderTraverse = (node = tree, cb = () => {}) => { if(!node) return cb(node.value) preOrderTraverse(node.left) preOrderTraverse(node.right)
/**
* 中序遍历
* left -> root -> right
*/
const inOrderTraverse = (node = tree, cb = () => {}) => { if(!node) return inOrderTraverse(node.left) cb(node.value) inOrderTraverse(node.right) }
/**
* 后续遍历
* left -> right -> root
*/
const postOrderTraverse = (node = tree, cb= () => {}) => { if(!node) return postOrderTraverse(node.left) postOrderTraverse(node.right) cb(node.value) }
前序:A->B->D->E->C->F->G
function preTraverStack(root,cb){ let stack = new Stack() stack.push(root) while(!stack.isEmpty()){ let node = stack.pop() if(node.right != null){ stack.push(node.right) } if(node.left != null){ stack.push(node.left) } cb(node.val) } }
function preTraver(root,cb){ let arr = [] arr.push(root) while(arr.length != 0){ let node = arr.pop() if(node.right != null){ arr.push(node.right) } if(node.left != null){ arr.push(node.left) } cb(node.val) } }
中序:D->B->E->A->F->C->G
function inTraverStack(root,cb){ let stack = new Stack() stack.push(root) while(!stack.isEmpty()){ while(stack.peek().left != null){ stack.push(stack.peek().left) } while(!stack.isEmpty()){ let node = stack.pop() cb(node.val) if(node.right != null){ stack.push(node.right) break } } } }
function inTraver(root,cb){ let arr = [] arr.push(root) while(arr.length != 0){ while(arr[arr.length - 1].left != null){ arr.push(arr[arr.length - 1].left) } while(arr.length != 0){ let node = arr.pop() cb(node.val) if(node.right != null){ arr.push(node.right) break } } } }
后序:D->E->B->F->G->C->A
function postTraverStack(root,cb){ let stack = new Stack() stack.push(root) let lastNode = null while(!stack.isEmpty()){ while(stack.peek().left != null){ stack.push(stack.peek().left) } while(!stack.isEmpty()){ if(lastNode == stack.peek().right || stack.peek().right == null){ let node = stack.pop() cb(node.val) lastNode = node }else if(stack.peek().right != null){ stack.push(stack.peek().right) break } } } }
以自己现在的努力程度,还没有资格和别人拼天赋