[二叉数]二叉树的深度优先遍历(统一迭代法)

一、题目描述

原文链接:144. 二叉树的前序遍历


具体描述:
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

示例 1:
在这里插入图片描述

输入:root = [1,null,2,3]
输出:[1,2,3]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

示例 4:
在这里插入图片描述

输入:root = [1,2]
输出:[1,2]

示例 5:
在这里插入图片描述

输入:root = [1,null,2]
输出:[1,2]

提示:

  • 树中节点数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

进阶:递归算法很简单,你可以通过迭代算法完成吗?


原文链接:145. 二叉树的后序遍历


具体描述:
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。

示例 1:
在这里插入图片描述

输入:root = [1,null,2,3]
输出:[3,2,1]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

提示:

  • 树中节点的数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

进阶:递归算法很简单,你可以通过迭代算法完成吗?


原文链接:94. 二叉树的中序遍历


具体描述:
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

示例 1:
在这里插入图片描述

输入:root = [1,null,2,3]
输出:[1,3,2]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

提示:

  • 树中节点数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

进阶: 递归算法很简单,你可以通过迭代算法完成吗?


二、思路分析

上次写的迭代法,前序和后序的写法差不多,但是中序个他们不一样,因为访问元素的顺序和中序的访问顺序是不一样的,所以不能写的一样!
但是看到递归的写法,如此的简单并且统一!羡慕呀,能不能把迭代的写法统一那,当然可以,而且并不难!

因为访问元素的顺序和深度优先遍历的顺序不一样,所以我们是不是可以先全部访问完,然后在开始处理元素那!
那还是用栈来做,根据栈的特点,在访问元素的时候要按照反顺序添加,如果前序是根左右,所以添加元素的时候是右左根!


三、AC代码

前序:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        if (root != null) stack.push(root);

        while (stack.empty() == false){
            TreeNode node = stack.pop();
            if (node != null) {
                // 根左右==》右左根
                if (node.right != null) stack.push(node.right);
                if (node.left != null) stack.push(node.left);

                stack.push(node);
                stack.push(null);
                
            }else{
                result.add(stack.pop().val);
            }
        }

        return result;
    }
}

中序:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root != null) stack.push(root);
        while (stack.empty() == false){
            TreeNode node = stack.pop();
            if (node != null){
                // 先添加右,在根,在左
                if (node.right != null) stack.push(node.right);

                stack.push(node);
                stack.push(null);// 标记根节点,尚未处理

                if (node.left != null) stack.push(node.left);

            }else{// 当前元素为空,说明到了需要处理的时候
                result.add(stack.pop().val);
            }
        }

        return result;
    }

}

后序:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root != null) stack.push(root);
        while (stack.empty() == false){
            TreeNode node = stack.pop();
            
            if (node != null){
                // 根右左
                stack.push(node);
                stack.push(null);

                if (node.right != null) stack.push(node.right);

                if (node.left != null) stack.push(node.left); 
            }else {
                result.add(stack.pop().val);
            }
        }
        return result;
    }
}

四、总结

  • 跟递归一样统一写法,还是很香的~

感谢大家的阅读,我是Alson_Code,一个喜欢把简单问题复杂化,把复杂问题简单化的程序猿!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java实现二叉树深度优先可以使用递归或者栈来实现。递归方比较简单,可以按照先序遍、中序遍和后序遍的方式进行深度优先。下面是一段示例代码,演示了Java中使用递归实现深度优先的方: ``` public class BinaryTree { // 定义二叉树节点类 public class TreeNode { public TreeNode leftNode; public TreeNode rightNode; public Integer val; public TreeNode(Integer val) { this.val = val; } } // 深度优先-先序遍 public void startErgodic(TreeNode node) { if (node == null) { return; } System.out.print(node.val + " "); startErgodic(node.leftNode); startErgodic(node.rightNode); } // 深度优先-中序遍 public void midErgodic(TreeNode node) { if (node == null) { return; } midErgodic(node.leftNode); System.out.print(node.val + " "); midErgodic(node.rightNode); } // 深度优先-后序遍 public void endErgodic(TreeNode node) { if (node == null) { return; } endErgodic(node.leftNode); endErgodic(node.rightNode); System.out.print(node.val + " "); } // 二叉树的插入操作 public void insert(Integer val) { // 插入操作的具体实现代码 } // 二叉树的递归插入操作 public void insertDigui(Integer val, TreeNode node) { // 递归插入操作的具体实现代码 } // 广度优先遍 public void Order() { // 广度优先遍的具体实现代码 } } public class Test { public static void main(String[] args) { BinaryTree binaryTree = new BinaryTree(); // 创建二叉树并进行插入操作 // 深度优先-先序遍 binaryTree.startErgodic(binaryTree.root); System.out.println(); // 深度优先-中序遍 binaryTree.midErgodic(binaryTree.root); System.out.println(); // 深度优先-后序遍 binaryTree.endErgodic(binaryTree.root); } } ``` 上述代码中的`startErgodic()`方实现了二叉树深度优先先序遍,`midErgodic()`方实现了中序遍,`endErgodic()`方实现了后序遍。可以根据需要选择相应的方进行遍。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Java实现二叉树深度优先和广度优先遍示例](https://download.csdn.net/download/weixin_38518885/12761000)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [java有序二叉树深度优先和广度优先遍](https://blog.csdn.net/m566666/article/details/122280365)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值