JS二叉树的三种遍历【迭代】

柔情只为你懂 2022-09-04 02:44 251阅读 0赞

前序遍历lc.144

迭代法

  1. var preorderTraversal = function(root) {
  2. // 初始化数据
  3. const res =[];
  4. const stack = [];
  5. while (root || stack.length){
  6. while(root){
  7. res.push(root.val);
  8. stack.push(root);
  9. root = root.left;
  10. }
  11. root = stack.pop();
  12. root = root.right;
  13. }
  14. return res;
  15. };

中序遍历lc.94

迭代法

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

后序遍历lc.145

迭代法

  1. var postorderTraversal = function(root) {
  2. // 初始化数据
  3. const res =[];
  4. const stack = [];
  5. while (root || stack.length){
  6. while(root){
  7. stack.push(root);
  8. res.unshift(root.val);
  9. root = root.right;
  10. }
  11. root = stack.pop();
  12. root = root.left;
  13. }
  14. return res;
  15. };

发表评论

表情:
评论列表 (有 0 条评论,251人围观)

还没有评论,来说两句吧...

相关阅读

    相关 顺序】

    1、中序遍历 指对树中任意节点的访问是在遍历完其左子树后进行的,访问此节点后,再对其右子树遍历(左根右)。遍历从根节点开始,遇到每个节点时,其遍历过程为: 中序遍

    相关

    二叉树的遍历分为以下三种: 先序遍历:遍历顺序规则为【根左右】 中序遍历:遍历顺序规则为【左根右】 后序遍历:遍历顺序规则为【左右根】 什么是【根左右】?就是先遍历根,