壹|什么是二叉树

二叉树有两个子节点,并不要求每个节点都有两个子节点。
满二叉树是每个节点都有两个子节点。
完全二叉树是除了最后一层,上面是满二叉树,且最后一层节点都靠左对齐。
二叉搜索树是一个有序树。左子树节点的值小于跟节点的值,右子树的值大于跟节点的值。
平衡二叉搜索树是二叉搜索树,且两个子树高度差不超过1。

贰|二叉树的遍历

深度优先遍历

  • 前序遍历
  • 中序遍历
  • 后续遍历 ```javascript 前序遍历递归: var preorderTraversal = function(root) { let res = []; const dfs = function(root){ if(root === null) return; res.push(root.val); dfs(root.left); dfs(root.right); } dfs(root); return res; };

前序遍历迭代: var preorderTraversal = function(root, res = []) { if(!root) return res; const stack = [root]; let cur = null; while(stack.length) { cur = stack.pop(); res.push(cur.val); cur.right && stack.push(cur.right); cur.left && stack.push(cur.left); } return res; };

中序遍历递归: var inorderTraversal = function(root) { let res = []; const dfs = function(root){ if(root === null){ return ; } dfs(root.left); res.push(root.val); dfs(root.right); } dfs(root); return res; };

中序遍历迭代: var inorderTraversal = function(root, res = []) { const stack = []; let cur = root; while(stack.length || cur) { if(cur) { stack.push(cur); cur = cur.left; } else { cur = stack.pop(); res.push(cur.val); cur = cur.right; } }; return res; };

后序遍历递归: var postorderTraversal = function(root) { let res = []; const dfs = function(root){ if(root === null){ return ; } dfs(root.left); dfs(root.right); res.push(root.val); } dfs(root); return res; };

后序遍历迭代: var postorderTraversal = function(root, res = []) { if (!root) return res; const stack = [root]; let cur = null; do { cur = stack.pop(); res.push(cur.val); cur.left && stack.push(cur.left); cur.right && stack.push(cur.right); } while(stack.length); return res.reverse(); };

  1. <a name="Vimln"></a>
  2. ### 广度优先遍历
  3. - 层次遍历
  4. ```javascript
  5. var levelOrder = function(root) {
  6. let res = [],queue = [];
  7. queue.push(root);
  8. if(root === null){
  9. return res;
  10. }
  11. while(queue.length){
  12. let length = queue.length;
  13. let curLevel = [];
  14. for(let i = 0; i < length; i++){
  15. let node = queue.shift();
  16. curLevel.push(node.val);
  17. node.left && queue.push(node.left);
  18. node.right && queue.push(node.right);
  19. }
  20. res.push(curLevel);
  21. }
  22. return res;
  23. };