Java实现二叉树的前中后序遍历(Leetcode)

本文深入解析了二叉树的前序、中序和后序遍历算法,通过迭代方式实现,详细展示了每种遍历方法的具体步骤和代码实现,是理解二叉树遍历机制的实用指南。

摘要生成于 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) {
        List<Integer>list=new ArrayList<Integer>();
        Stack<TreeNode>stack=new Stack<TreeNode>();
        
        while(root!=null||!stack.isEmpty()){
            while(root!=null){
            list.add(root.val);
            stack.push(root);
                root=root.left;
            }
            if(!stack.isEmpty()){
                root=stack.pop();
                root=root.right;
            }
        }
        return list;
    }
}

中序迭代遍历:

/**
 * 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) {
        List<Integer> list=new ArrayList<Integer>();
        Stack<TreeNode>stack=new Stack<TreeNode>(); 
        while(root!=null||!stack.isEmpty()) {
        while(root!=null) {//先将左结点入栈
        	stack.push(root);
        	root=root.left;
        }
        if(!stack.empty()) {
        	root=stack.pop();
        	list.add(root.val);
        	root=root.right;//如果当前结点有右结点遍历它的右结点
        }
        }
        return list;
    }
}

后序迭代遍历:

/**
 * 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) {
        List<Integer>list=new ArrayList<Integer>();
        Stack<TreeNode>stack=new Stack<TreeNode>();
        TreeNode q=null;
         while(root!=null||!stack.isEmpty()) {
        while(root!=null) {
        	stack.push(root);
        	root=root.left;
        }
             if(!stack.empty()) {
        	root=stack.peek();//取得结点但不让它出栈
            if((root.right==null)||(root.right==q)){//判断该节点的右结点是否访问过
                stack.pop();
                list.add(root.val);
                q=root;
                root=null;
            }
                 else{
                     root=root.right;
                 }
        }
        }
        return list;
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值