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 inorderTraverStack(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 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 } } } }
原文:https://www.cnblogs.com/zhenjianyu/p/13305132.html