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
| function TreeNode(val) { this.val = val; this.left = null; this.right = null; }
function createTree_levelorder(arr) { let rootval = arr.shift(); let queue = []; if (rootval) { let root = new TreeNode(rootval); queue.push(root); while (queue.length) { let node = queue.shift(); let leftval = arr.shift(); let rightval = arr.shift(); if (leftval !== '#') { let left = new TreeNode(leftval); queue.push(left); node.left = left; } if (rightval !== '#') { let right = new TreeNode(rightval); queue.push(right); node.right = right; }
} return root; } }
let arr = ['a', 'b', 'c', 'd', '#', '#', 'e', '#', 'f', '#', '#', '#', '#']; let root = createTree_levelorder(arr);
function PreOrder(root, arr = []) { if (root) { arr.push(root.val); PreOrder(root.left, arr); PreOrder(root.right, arr); } else { arr.push('#'); } } let res = []; PreOrder(root, res); console.log(res);
function InOrder(root, arr = []) { if (root) { InOrder(root.left, arr); arr.push(root.val); InOrder(root.right, arr); } else { arr.push('#'); } } let res2 = []; InOrder(root, res2); console.log(res2);
function PostOrder(root, arr = []) { if (root) { PostOrder(root.left, arr); PostOrder(root.right, arr); arr.push(root.val); } else { arr.push('#'); } } let res3 = []; PostOrder(root, res3); console.log(res3);
|