二叉树的遍历
前序遍历
递归:
function preorderTraversal(root) {if (root === null) {return}console.log(root.val)inorderTraversal(root.left)inorderTraversal(root.right)}
迭代:
function preorderTraversal(root) {const stack = [root]while (stack.length > 0) {const node = stack.pop()if (node === null) {continue}console.log(node.val)stack.push(node.right)stack.push(node.left)}}
中序遍历:
递归:
function inorderTraversal(root) {if (root === null) {return}inorderTraversal(root.left)console.log(root.val)inorderTraversal(root.right)}
迭代:
function inorderTraversal(root) {const stack = []while (root || stack.length > 0) {if (root) {stack.push(root)root = root.left} else {root = stack.pop()console.log(root.val)root = root.right}}}
后序遍历:
递归:
function postorderTraversal(root) {if (root === null) {return}inorderTraversal(root.left)inorderTraversal(root.right)console.log(root.val)}
迭代:
function postorderTraversal(root) {const stack = []let prev = nullwhile (root || stack.length > 0) {if (root) {stack.push(root)root = root.left} else {root = stack.pop()if (!root.right || root.right === prev) {console.log(root.val)prev = rootroot = null} else {stack.push(root)root = root.right}}}}
层序遍历:
function levelOrder(root) {if (root === null) {return}const queue = [root]while (queue.length > 0) {const node = queue.shift()console.log(node.val)if (node.left) {queue.push(node.left)}if (node.right) {queue.push(node.right)}}}
二叉搜索树
完美二叉树
满二叉树
线索二叉树
