• 二叉树的前序中序后序遍历-非递归-使用同一段代码实现


    树的遍历通常使用递归,因为它的实现更简单,代码也更容易理解。

    但在面试,或者特殊的情境中会使用到迭代算法(非递归)。

    此时需要使用栈去模拟函数栈调用过程。

    本文将给出一段代码去实现这三种遍历

    相比于传统的方式:前序遍历,中序遍历,后序遍历,使用不同的方式代码去实现,并且后续遍历更为难理解一些

    可拓展性更好(比如N叉树的遍历),也更容易理解

    考虑,对于一个函数栈,它除了存储了一些变量和指令,同时还存储了当前执行位置

    对于树的遍历,无非为:t->val,t->left ,t->right 三个代码的排列

    因此,我们只需定义一个int类型的变量,用于记录当前执行到哪一个代码。

     1     class TreeNodeWithIndex{
     2         public TreeNode node;
     3         public int index=0;
     4         public TreeNodeWithIndex(TreeNode n) { node = n; }
     5     }
        //0 pre ; 1 inorder ; 2 post 
    6 public IList<int> TreeTraversal(TreeNode root,int type) 7 { 8 var stack = new Stack<TreeNodeWithIndex>(); 9 var ans = new List<int>(); 10 stack.Push(new TreeNodeWithIndex(root)); 11 while (stack.Count!=0) 12 { 13 var i = stack.Peek(); 14 if (i.index > 2 || i.node == null) { stack.Pop(); continue; } 15 if (type == i.index) ans.Add(i.node.val); 16 else 17 { 18 int tmp = type - i.index * 2; 19 if (tmp > 0 || tmp == -2) 20 stack.Push(new TreeNodeWithIndex(i.node.left)); 21 else 22 stack.Push(new TreeNodeWithIndex(i.node.right)); 23 } 24 i.index++; 25 } 26 return ans; 27 }
  • 相关阅读:
    async/await
    js继承
    js处理上下文代码的2个阶段
    js相关地址
    vue自定义指令钩子函数
    vue 组件
    vue methods和computed,v-show和v-if
    vue 生命周期
    DOM操作——怎样添加、移除、移动、复制、创建和查找节点
    js 传递参数
  • 原文地址:https://www.cnblogs.com/lightz/p/9678606.html
Copyright © 2020-2023  润新知