当前位置: 首页 > article >正文

Java数据结构第十六期:走进二叉树的奇妙世界(五)

专栏:Java数据结构秘籍

个人主页:手握风云

目录

一、非递归实现遍历二叉树

1.1. 二叉树的前序遍历

1.2. 二叉树的中序遍历

1.3. 二叉树的后序遍历


一、非递归实现遍历二叉树

1.1. 二叉树的前序遍历

        我们这里要使用栈来进行实现。我们反向思考一下为什么不使用队列?如下图,前序遍历肯定是先将根结点放进去,如果是队列,根结点先进先出,然后怎么去遍历右子树呢,就无法打印的顺序了。

        我们定义一个引用cur,只要cur不为null,就打印值并将该元素放入栈中。当遍历到4时,左子树为空,返回结点4并弹出,再去遍历4的右结点,然后返回结点2并弹出,让cur等于结点2的右子树并遍历。只要1的左子树没有遍历完,1就不弹出。

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

        代码写到这里就会出现问题,原因是:当遍历到结点4的时候,4的左子树为空,就无法进入while循环。然后把4弹出去,让cur=top,问题又来了,如果结点4左边要是不为空,又得放入栈中,也需要走while循环。

        我们会发现当cur走到某个结点时,如果为空,但栈不为空,此时就可以巧妙地在while外面再加一层while循环。

while (cur != null || !stack.isEmpty()) {
    while (cur != null) {
        stack.push(cur);
        System.out.print(cur.val + " ");
        cur = cur.left;
    }
    cur = stack.pop();
    cur = cur.right;
}

        完整代码实现:

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode() {}

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public List<Integer> preorderTraversal(TreeNode root){
        List<Integer> tree = new ArrayList<>();

        if(root == null){
            return tree;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                tree.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            cur = cur.right;
        }
        return tree;
    }
}
import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Integer> result = new ArrayList<>();
        Solution solution = new Solution();

        TreeNode root = new TreeNode(1,new TreeNode(2),new TreeNode(3));
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.left.right.left = new TreeNode(6);
        root.left.right.right = new TreeNode(7);
        root.right.right = new TreeNode(8);
        root.right.right.left = new TreeNode(9);

        result = solution.preorderTraversal(root);
        System.out.println(result);
    }
}

1.2. 二叉树的中序遍历

        与前序遍历的思路相同,只是打印的时机不一样。中序遍历要在弹出的元素之后直接打印。

        完整代码实现:

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode() {}

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root){
        List<Integer> tree = new ArrayList<>();

        if(root == null){
            return tree;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                tree.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            tree.add(cur.val);
            cur = cur.right;
        }
        return tree;
    }
}
import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Integer> result = new ArrayList<>();
        Solution solution = new Solution();

        TreeNode root = new TreeNode(1,new TreeNode(2),new TreeNode(3));
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.left.right.left = new TreeNode(6);
        root.left.right.right = new TreeNode(7);
        root.right.right = new TreeNode(8);
        root.right.right.left = new TreeNode(9);

        result = solution.inorderTraversal(root);
        System.out.println(result);
    }
}

1.3. 二叉树的后序遍历

        后序遍历不能按照我们上面前序与中序的方法来做。如果结点下面还有孩子结点,如果把4弹出之后,就无法获取它的右侧,所以只能获取不能弹出。当右子树为空,才能弹出,再进行打印。

public class Solution {
    public void postorderTraversal(TreeNode root){
        if(root == null){
            return;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();
            if(top.right == null){
                stack.pop();
                System.out.print(top.val+" ");
            }else{
                cur = top.right;
            }
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Solution solution = new Solution();

        TreeNode root = new TreeNode(1,new TreeNode(2),new TreeNode(3));
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.left.right.right = new TreeNode(7);
        root.right.right = new TreeNode(8);
        root.right.right.left = new TreeNode(9);

        solution.postorderTraversal(root);
    }
}

        但这样写,会存在问题:当遍历到结点5的右结点7时,会陷入死循环。那我们怎么知道这个结点被打印过?我们再定义引用prev,让prev来记录被弹出的结点。

        while(cur != null || !stack.isEmpty()) {
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();
            if(top.right == null || top.right == prev){
                stack.pop();
                System.out.print(top.val+" ");
                prev = top;
            }else{
                cur = top.right;
            }

        完整代码实现:

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode() {}

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root){
        List<Integer> tree = new ArrayList<>();

        if(root == null){
            return tree;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        TreeNode prev = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();
            if(top.right == null || top.right == prev){
                tree.add(top.val);
                stack.pop();
                prev = top;
            }else{
                cur = top.right;
            }
        }
        return tree;
    }
}
import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Integer> tree = new ArrayList<>();
        Solution solution = new Solution();

        TreeNode root = new TreeNode(1,new TreeNode(2),new TreeNode(3));
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.left.right.left = new TreeNode(6);
        root.left.right.right = new TreeNode(7);
        root.right.right = new TreeNode(8);
        root.right.right.left = new TreeNode(9);

        tree = solution.postorderTraversal(root);
        System.out.println(tree);
    }
}

http://www.kler.cn/a/568347.html

相关文章:

  • 【QT线程】子线程阻塞主线程的一次网络api请求案例
  • 自然语言处理算法工程师的技术图谱和学习路径
  • 代码随想录算法训练day66---图论系列10《Bellman_ford 队列优化算法负权回路单源有限最短路》
  • 26、IO流(只是小入门)
  • IDEAPyCharm安装ProxyAI(CodeGPT)插件连接DeepSeek-R1教程
  • Ollama 的庐山真面目
  • 【树莓派学习】树莓派3B+的安装和环境配置
  • GIT工具学习【1】:基本操作
  • 数据库Redis数据库
  • 【中等】707.设计链表
  • zookeeper-docker版
  • JVM基础概念作用类加载运行时数据区执行引擎本地方法
  • 5G学习笔记之BWP
  • 【Java基础】Java 中 的`final` 关键字
  • 【计算机网络入门】初学计算机网络(六)
  • 车载电源管理新标杆NCV8460ADR2G 在汽车电子负载开关中的应用
  • 基于STM32单片机物联网智能浇花系统设计
  • 请解释 Node.js 中的网络模块(http、https),如何创建 HTTP服务器?
  • 基于微信小程序的疫情互助平台(源码+lw+部署文档+讲解),源码可白嫖!
  • HTMLS基本结构及标签