Leetcode刷题java之二叉树的前序中序后续遍历非递归实现(一天一道编程题之二十四天)

本文深入解析了二叉树的前序、中序和后序遍历算法,通过详细的代码实现,帮助读者理解每种遍历方式的原理及应用。文章涵盖了二叉树节点定义、遍历流程及其实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前序遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        TreeNode cur=root;
        Stack<TreeNode> stack=new Stack<>();
        List<Integer> result=new ArrayList<>();
        while(!stack.isEmpty()||cur!=null)
        {
            while(cur!=null)
            {
                result.add(cur.val);
                stack.push(cur);
                cur=cur.left;
            }
            //取出一个进行回溯
            cur=stack.pop();
            cur=cur.right;
        }
        return result;
    }
}

中序遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        TreeNode cur=root;
        Stack<TreeNode> stack=new Stack<>();
        List<Integer> result=new ArrayList<>();
        while(!stack.isEmpty()||cur!=null)
        {
            while(cur!=null)
            {
                stack.push(cur);
                cur=cur.left;
            }
            cur=stack.pop();
            //从栈中取出一个对右进行回溯
            result.add(cur.val);
            cur=cur.right;
        }
        return result;
    }
}

后序遍历:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        TreeNode cur=root;
        TreeNode last=null;
        Stack<TreeNode> stack=new Stack<>();
        List<Integer> result=new ArrayList<>();
        while(!stack.isEmpty()||cur!=null)
        {
            while(cur!=null)
            {
                stack.push(cur);
                cur=cur.left;
            }
            TreeNode top=stack.peek();
            if(top.right==null||top.right==last)
            {
                result.add(top.val);
                stack.pop();
                last=top;
            }else
            {
                cur=top.right;
            }
        }
        return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值