二叉树的后序遍历(递归方式和非递归方式)

二叉树的后序遍历为先遍历左子树,再遍历右子树,最后获取根节点的值。
递归方式和先序,中序类似。

public class Solution {

    public int[] postorderTraversal (TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root==null){
            return new int[0];
        }
        dfs(list,root);
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
    
    public void dfs(List<Integer> list,TreeNode root){
        if(root.left!=null){
            dfs(list,root.left);
        }
        if(root.right!=null){
            dfs(list,root.right);
        }
        list.add(root.val);
    }
    
}

非递归方式

    public int[] postorderTraversal (TreeNode root) {
        if(root==null){
            return new int[0];
        }
        Stack<TreeNode> s1 = new Stack<>();
        Stack<TreeNode> s2 = new Stack<>();
        TreeNode p = root;
        s1.push(p);
        while(!s1.empty()){
            p=s1.pop();
            s2.push(p);
            if(p.left!=null){
                s1.push(p.left);
            }
            if(p.right!=null){
                s1.push(p.right);
            }
        }
        int[] res = new int[s2.size()];
        for(int i=0;i<res.length;i++){
            res[i] = s2.pop().val;
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值