树的遍历

前序遍历:中-左-右

  1. var preorderTraversal = function(root) {
  2. if(!root) return []
  3. var number = []
  4. number.push(root.val)
  5. number = number.concat(preorderTraversal(root.left))
  6. number = number.concat(preorderTraversal(root.right))
  7. return number
  8. };

中序遍历:左-中-右

  1. var inorderTraversal = function(root) {
  2. if(!root) return [];
  3. var num = []
  4. num = num.concat(inorderTraversal(root.left));
  5. num.push(root.val);
  6. num = num.concat(inorderTraversal(root.right))
  7. return num
  8. };

后序遍历:左-右-中

  1. var postorderTraversal = function(root) {
  2. if(!root) return [];
  3. var num = []
  4. num = num.concat(postorderTraversal(root.left));
  5. num = num.concat(postorderTraversal(root.right))
  6. num.push(root.val);
  7. return num
  8. };

总结: 记不住前中后遍历的顺序的同学可以记住 前中后遍历是针对根节点来说的,而左节点一直在右节点前面,前序遍历即中节点-左-右,后序即中节点在最后,即左-右-中

层序遍历广度优先搜索

先访问根节点及相邻节点,再遍历二级节点,随后是三级节点