145. Binary Tree Postorder Traversal

本文介绍了一种解决二叉树后序遍历问题的两种方法:递归和迭代。递归方法简洁明了,而迭代方法使用栈来实现,避免了递归的深度限制。两种方法均能有效返回二叉树节点值的后序遍历结果。

题目描述

Given a binary tree, return the postorder traversal of its nodes’ values.
在这里插入图片描述

方法思路

Approach1: recursive

class Solution {
    //Runtime: 0 ms, faster than 100.00%
    //Memory Usage: 36.2 MB, less than 25.53%
    List<Integer> res = new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
        if(root == null) return res;
        postorderTraversal(root.left);
        postorderTraversal(root.right);
        res.add(root.val);
        
        return res;
    }
} 

Approach2:iteratively

class Solution{
    //Runtime: 0 ms, faster than 100.00%
    //Memory Usage: 36.3 MB, less than 14.74% 
    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> res = new LinkedList<>();
        if(root == null) return res;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            res.addFirst(node.val);
            if(node.left != null)//判断左右子树是否为null,否则会有空指针异常
                stack.push(node.left);
            if(node.right != null)
                stack.push(node.right);
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值