[LeetCode 145. 二叉树的后序遍历] |刷题打卡

114 阅读1分钟

一、题目描述:

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

示例:

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

输出: [3,2,1]

引自:leetcode-cn.com/problems/bi…

题目链接:145. 二叉树的后序遍历

二、思路分析:

二叉树的后序遍历按照左子树、右子树、根节点的顺序来访问。

考虑使用递归的方式来解决。

按照递归顺序性访问左子树、右子树、根节点。并且把相应值放到数组中。

三、AC 代码:

class Solution {
    var resultArr : [Int] = [Int]();
    func postorderTraversal(_ root: TreeNode?) -> [Int] {
        if (root == nil) {
            // 空树
            return [Int]();
        }
        postorderTraversal(root?.left);
        postorderTraversal(root?.right);
        let tempValue : Int = root?.val ?? 0;
        resultArr.append(tempValue);
        return resultArr;
    }
}

四、参考学习网址

二叉树

本文正在参与「掘金 3 月闯关活动」, 点击查看 活动详情