0
点赞
收藏
分享

微信扫一扫

leetcode算法145.二叉树的后序遍历

kiliwalk 2022-02-23 阅读 46

文章目录

一、leetcode算法

1、二叉树的后序遍历

1.1、题目

示例 1:

输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2:

输入:root = []
输出:[]
示例 3:

输入:root = [1]
输出:[1]

1.2、思路

1.3、答案

在这里插入图片描述

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        postorder(root,res);
        return res;
    }
    public void postorder(TreeNode root,List<Integer> res){
        if(root == null){
            return;
        }

        postorder(root.left,res);
        postorder(root.right,res);
        res.add(root.val);
    }
}

复杂度分析

时间复杂度:O(n),其中 n 是二叉搜索树的节点数。每一个节点恰好被遍历一次。

空间复杂度:O(n),为递归过程中栈的开销,平均情况下为 O(logn),最坏情况下树呈现链状,为 O(n)。

举报

相关推荐

0 条评论