Open Jason-linjiayu opened 3 years ago
const preOrder =(root)=> {
if(!root) return
console.log(root.val)
if(root.left) preOrder(root.left)
if(root.right) preOrder(root.right)
}
preOrder(tree) // 1245367
const preOrder = (root) => {
if(!root) return
const stack = [root]
while(stack.length) {
const n = stack.pop();
console.log(n.val)
if(n.right) stack.push(n.right)
if(n.left) stack.push(n.left)
}
}
preOrder(tree) //1245367
const inOrder = (root) => {
if(!root) return
if(root.left) inOrder(root.left)
console.log(root.val)
if(root.right) inOrder(root.right)
}
inOrder(tree) // 4251637
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) // 4251637
const postOrder = (root) => {
if(!root) return
if(root.left) postOrder(root.left)
if(root.right) postOrder(root.right)
console.log(root.val)
}
postOrder(tree) // 4526731
const postOrder = (root) => {
if(!root) return
const stack = [root]
const outputStack = []
while(stack.length) {
const n = stack.pop()
outputStack.push(n)
if(n.left ) stack.push(n.left)
if(n.right) stack.push(n.right)
}
while(outputStack.length) {
const p = outputStack.pop()
console.log(p.val)
}
}
postOrder(tree)
const inOrder = [9,3,15,20,7]
const postOrder = [9,15,7,20,3]
const getTree = (inOrder, postOrder) => {
if(!inOrder.length || !postOrder.length) return null
const root = postOrder[postOrder.length - 1];
const rootIndex = inOrder.indexOf(root)
const leftInOrder = inOrder.slice(0,rootIndex)
const rightInOrder = inOrder.slice(rootIndex+1)
const leftPostOrder = postOrder.slice(0,rootIndex)
const rightPostOrder = postOrder.slice(rootIndex, postOrder.length-1)
return {
val: root,
left: getTree(leftInOrder,leftPostOrder),
right: getTree(rightInOrder, rightPostOrder)
}
}
const tree = getTree(inOrder,postOrder)
const dfs = (root) => {
if(!root) return;
console.log(root.val)
if(root.left)dfs(root.left)
if(root.right) dfs(root.right)
}
dfs(tree)
先放颗二叉树