一、前序遍历
const preorderTraversal = (root) => { const list = [] const stack = [] if(root) { stack.push(root) } while(stack.length > 0) { let curNode = stack.pop() list.push(curNode.val) if(curNode.right !== null) { stack.push(curNode.right) } if(curNode.left !== null) { stack.push(curNode.left) } } return list}
二、中序遍历
const inorderTraversal = (root) => { const list = [] const stack = [] let node = root while(node || stack.length){ while(node) { stack.push(node) node = node.left } node = stack.pop() list.push(node.val) node = node.right } reutrn list}
三、后序遍历
const postorderTraversal = (root) => { const list = [] const stack = [] if(root) { stack.push(root) } while(stack.length > 0) { let curNode = stack.pop() list.unshift(curNode.val) if(curNode.left !== null) { stack.push(curNode.left) } if(curNode.right !== null) { stack.push(curNode.right) } } return list}
四、二叉树的深度
const maxDepth = function(root) { if(root == null) { return 0 }else{ let left = maxDepth(root.left) let right = maxDepth(root.right) return Math.max(left, right) + 1 }};
五、二叉树层序遍历
//BFSvar levelOrder = function(root) { if(root == null) { return [] } let res = [] let queue = [root] while(queue.length > 0) { let len = queue.length let arr = [] while(len) { let node = queue.shift() arr.push(node.val) if(node.left) { queue.push(node.left) } if(node.right) { queue.push(node.right) } len-- } res.push(arr) } return res}
六、翻转二叉树
var invertTree = function(root) { if(root == null) { return null } let left = invertTree(root.left) let right = invertTree(root.right) root.left = right root.right = left return root};