首页 > 其他分享 >遍历二叉树非递归实现

遍历二叉树非递归实现

时间:2024-01-22 14:55:40浏览次数:36  
标签:遍历 cur 递归 Stack 二叉树 push null root stack

实现

1. 前序遍历

public void preOrderNor(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            System.out.print(cur.val + " ");
            if (cur.right != null) {
                stack.push(cur.right);
            }
            if (cur.left != null) {
                stack.push(cur.left);
            }
        }
    }

力扣测试

class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> ret = new ArrayList<>();
            if (root == null) {
                return ret;
            }
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while (!stack.isEmpty()) {
                TreeNode cur = stack.pop();
                ret.add(cur.val);
                if (cur.right != null) {
                    stack.push(cur.right);
                }
                if (cur.left != null) {
                    stack.push(cur.left);
                }
            }
            return ret;
        }
    }

 

2. 中序遍历

public void inOrderNor(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            }else {
                root = stack.pop();
                System.out.println(root.val + " ");
                root = root.right;
            }
        }
    }

力扣测试

class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {

            List<Integer> ret = new ArrayList<>();
            if (root == null) {
                return ret;
            }

            Stack<TreeNode> stack = new Stack<>();
            while (root != null || !stack.isEmpty()) {
                if (root != null) {
                    stack.push(root);
                    root = root.left;
                }else {
                    root = stack.pop();
                    ret.add(root.val);
                    root = root.right;
                }
            }
            return ret;
        }
}

3. 后序遍历

两个栈实现:

public  void posOrderTwoStacks(TreeNode root) {
        if (root != null) {
            Stack<TreeNode> stack = new Stack<>();
            Stack<TreeNode> collect = new Stack<>();
            stack.push(root);
            while (!stack.isEmpty()) {
                root = stack.pop();
                collect.push(root);
                if (root.left != null) {
                    stack.push(root.left);
                }
                if (root.right != null) {
                    stack.push(root.right);
                }
            }
            while (!collect.isEmpty()) {
                System.out.print(collect.pop().val + " ");
            }
        }
    }

 

一个栈实现:

public  void posOrderOneStacks(TreeNode root) {
        if (root != null) {
            // 标记上一次访问的节点
            TreeNode sign = root;
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while (!stack.isEmpty()) {
                TreeNode cur = stack.peek();
                // 如果sign标志右树 那么左树一定处理了
                if (cur.left != null && cur.left != sign && cur.right != sign) {
                    // 有左树且左树没有处理进来
                    stack.push(cur.left);
                }else if (cur.right != null && cur.right != sign) {
                    // 有右树且右树没有处理进来
                    stack.push(cur.right);
                }else {
                    System.out.print(cur.val + " ");
                    sign = stack.pop();
                }
            }
        }
    }

标签:遍历,cur,递归,Stack,二叉树,push,null,root,stack
From: https://www.cnblogs.com/xumu7/p/17979293

相关文章

  • Java中遍历方法对比
    DemopublicclassTest{publicstaticvoidmain(String[]args){test(10);test(100);test(1000);test(10000);}publicstaticvoidtest(intsize){//1.组装数组List<String>list=list(siz......
  • 二叉树面试题进阶
    二叉树面试题进阶1.二维数组存储层序遍历结果难点: 如何存储每一层的节点?根据队列节点的个数判断每一层classSolution{publicList<List<Integer>>levelOrder(TreeNoderoot){List<List<Integer>>retList=newArrayList<>();if(root==nu......
  • 实现创建二叉树
    创建二叉树1.前序遍历创建二叉树importjava.util.Scanner;//注意类名必须为Main,不要有任何packagexxx信息classTreeNode{publicTreeNodeleft;publiccharval;publicTreeNoderight;publicTreeNode(charval){this.val=......
  • 最少交换次数 置换环 LeetCode 2471. 逐层排序二叉树所需的最少操作数目
    voidMain(){ varroot=newTreeNode(1) { left=newTreeNode(3) { left=newTreeNode(7), right=newTreeNode(6) }, right=newTreeNode(2) { left=newTreeNode(5), right=newTreeNode(4) } }; varr=newSolution().Minimu......
  • 遍历二叉树
    二叉树前言二叉树的遍历主要有深度优先遍历和广度优先遍历,深度优先遍历是优先访问一个子树上的所有节点,访问的属性是竖向的,而广度优先遍历则是优先访问同一层的所有节点,访问属性是横向的。深度优先遍历深度优先遍历主要有三种顺序:前序遍历——根左右中序遍历——左根......
  • 详解匿名函数递归:从此能看懂天书代码
    最近在读《左耳听风》,里面提到了一个匿名函数递归的例子,觉得很有趣,但是我觉得书里讲解的还是有点难懂,所以尝试用自己的理解把这个问题重新讲了一遍。注:本文中所用的代码示例会同时使用JavaScript,Python语言。让我们先来看下面这段代码://javascript(f=>f(f))(f=>n=>n==......
  • 二叉树 - 二叉树入门题
    二叉树入门题1.判断两颗树是否相同classSolution{publicbooleanisSameTree(TreeNodep,TreeNodeq){//如何判断两颗树是否相同?根相同+左右子树相同//如何判断根相同?结构+值相同if(p==null&&q!=null||p!=null&&......
  • 动态规划(4) 完全背包的遍历顺序
    目录377组合总和Ⅳ进阶版爬楼梯322零钱兑换377组合总和ⅣclassSolution{public:intcombinationSum4(vector<int>&nums,inttarget){intn=nums.size();vector<int>dp(target+1,0);dp[0]=1;for(intj=0;j<=target;j++)......
  • 不创建临时变量求字符串长度--初识递归
    递归:一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法。递归的例题应用:不创建临时变量求字符串长度。intmy_strlen(char*str){ if(*str!='\0') { return1+my_strlen(str+1); } else return0;}intmain(){ chararr[]="bi......
  • 二叉树结构与递归实现前中后序遍历
    1.二叉树结构2.二叉树节点遍历顺序前序:每颗子树以中—》左—》右遍历ABDEHCFG 中序:每颗子树以左 —》中—》右遍历DBEHAFCG 后序:每颗子树以左 —》右—》中遍历DHEBFGCA 代码实现:publicclassBinaryTree{stat......