94. 二叉树的中序遍历

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

  • [x] iteration

  • [x] recursion

  • [ ] morris

  • iteration

  1. var inorderTraversal = function(root) {
  2. let stack = [];
  3. let res = [];
  4. while(root !== null || stack.length){
  5. while(root !== null){
  6. stack.push(root);
  7. root = root.left;
  8. }
  9. root = stack.pop();
  10. res.push(root.val);
  11. root = root.right;
  12. }
  13. return res;
  14. }
  • recursion
  1. var inorderTraversal = function(root) {
  2. let res = [];
  3. let dfs = (root) =>{
  4. if (root == null)return;
  5. dfs(root.left);
  6. res.push(root.val);
  7. dfs(root.right);
  8. }
  9. dfs(root);
  10. return res;
  11. };