1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
var postorderTraversal = function (root) { const ret = [] if (!root) return ret const s1 = [root] const s2 = [] while(s1.length){ const cur = s1.pop() s2.push(cur) if(cur.left) s1.push(cur.left) if(cur.right) s1.push(cur.right) } while(s2.length) ret.push(s2.pop().val)
return ret };
var postorderTraversal = function (root) { const ret = [] if (!root) return ret const s1 = [root] let h = root, cur while(s1.length){ cur = s1[s1.length-1] if(cur.left && h !== cur.left && h !== cur.right) s1.push(cur.left) else if( cur.right && h !== cur.right) s1.push(cur.right) else{ ret.push(s1.pop().val) h = cur } }
return ret };
class Command { constructor(s, node) { this.s = s this.node = node } }
var postorderTraversal = function (root) { let res = [] if (root === null) return res const stack = [] stack.push(new Command("go",root)) while(stack.length){ const command = stack.pop() if(command.s === 'print') res.push(command.node.val) else{ stack.push(new Command("print",command.node)) if(command.node.right) stack.push(new Command("go",command.node.right)) if(command.node.left) stack.push(new Command("go",command.node.left)) } } return res };
|