五句话完成二叉树的前中后序遍历!LeetCode 94 144 145(Java)

本文介绍了如何仅用五段代码实现二叉树的前序、中序和后序遍历,通过示例和Java代码展示了核心步骤,适合初学者快速掌握基本算法技巧。

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

只需以下五句代码排列组合即可解决二叉树的前序中序后序遍历问题:

res.add(root.val);
stack.push(root);
root=root.left;
TreeNode cur=stack.pop();
root=cur.right;

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]

Java:

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new ArrayDeque<>();

        while (root!=null||!stack.isEmpty()){
            while(root!=null){
                res.add(root.val);
                stack.push(root);
                root=root.left;
            }
            TreeNode cur=stack.pop();
            root=cur.right;
        }
        return res;
    }
}

145. 二叉树的后序遍历

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        Deque<TreeNode>stack=new ArrayDeque<>();

        while(root!=null||!stack.isEmpty()){
            while(root!=null){
                res.add(root.val);
                stack.push(root);
                root=root.right;
            }
            TreeNode cur=stack.pop();
            root=cur.left;
        }
        Collections.reverse(res);
        return res;
    }
}

94. 二叉树的中序遍历

给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
示例 4:
输入:root = [1,2] 输出:[2,1]
示例 5:
输入:root = [1,null,2] 输出:[1,2]

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        Deque<TreeNode>stack=new ArrayDeque<>();

        while(root!=null||!stack.isEmpty()){
            while(root!=null){
                stack.push(root);
                root=root.left;
            }
            root=stack.pop();
            res.add(root.val);
            root=root.right;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值