一、前序遍历

  1. const preorderTraversal = (root) => {
  2. const list = []
  3. const stack = []
  4. if(root) {
  5. stack.push(root)
  6. }
  7. while(stack.length > 0) {
  8. let curNode = stack.pop()
  9. list.push(curNode.val)
  10. if(curNode.right !== null) {
  11. stack.push(curNode.right)
  12. }
  13. if(curNode.left !== null) {
  14. stack.push(curNode.left)
  15. }
  16. }
  17. return list
  18. }

二、中序遍历

  1. const inorderTraversal = (root) => {
  2. const list = []
  3. const stack = []
  4. let node = root
  5. while(node || stack.length){
  6. while(node) {
  7. stack.push(node)
  8. node = node.left
  9. }
  10. node = stack.pop()
  11. list.push(node.val)
  12. node = node.right
  13. }
  14. reutrn list
  15. }

三、后序遍历

  1. const postorderTraversal = (root) => {
  2. const list = []
  3. const stack = []
  4. if(root) {
  5. stack.push(root)
  6. }
  7. while(stack.length > 0) {
  8. let curNode = stack.pop()
  9. list.unshift(curNode.val)
  10. if(curNode.left !== null) {
  11. stack.push(curNode.left)
  12. }
  13. if(curNode.right !== null) {
  14. stack.push(curNode.right)
  15. }
  16. }
  17. return list
  18. }

四、二叉树的深度

  1. const maxDepth = function(root) {
  2. if(root == null) {
  3. return 0
  4. }else{
  5. let left = maxDepth(root.left)
  6. let right = maxDepth(root.right)
  7. return Math.max(left, right) + 1
  8. }
  9. };

五、二叉树层序遍历

  1. //BFS
  2. var levelOrder = function(root) {
  3. if(root == null) {
  4. return []
  5. }
  6. let res = []
  7. let queue = [root]
  8. while(queue.length > 0) {
  9. let len = queue.length
  10. let arr = []
  11. while(len) {
  12. let node = queue.shift()
  13. arr.push(node.val)
  14. if(node.left) {
  15. queue.push(node.left)
  16. }
  17. if(node.right) {
  18. queue.push(node.right)
  19. }
  20. len--
  21. }
  22. res.push(arr)
  23. }
  24. return res
  25. }

六、翻转二叉树

  1. var invertTree = function(root) {
  2. if(root == null) {
  3. return null
  4. }
  5. let left = invertTree(root.left)
  6. let right = invertTree(root.right)
  7. root.left = right
  8. root.right = left
  9. return root
  10. };