94. Binary Tree Inorder Traversal 二叉树中序遍历

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

   1
    
     2
    /
   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

题意:不使用递归的方式,中序遍历二叉树


  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {number[]}
  11. */
  12. let inorderTraversal = (root) => {
  13. let res = [];
  14. if (root == null) return res;
  15. let stack = [];
  16. var node = root;
  17. while (node != null || stack.length != 0) {
  18. while (node != null) {
  19. stack.push(node);
  20. node = node.left;
  21. }
  22. if (stack.length != 0) {
  23. node = stack.pop();
  24. res.push(node.val)
  25. node = node.right;
  26. }
  27. }
  28. return res;
  29. }





原文地址:https://www.cnblogs.com/xiejunzhao/p/8127976.html