1 Star 2 Fork 1

theajack / leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
binary-tree-postorder-traversal.md 880 Bytes
一键复制 编辑 原始数据 按行查看 历史

题目描述

原题地址

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

示例:

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

输出: [3,2,1]

解题

比较常规的递归,按照后序遍历规则,先左后右

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function(root) {
    let res = [];
    var traversal = function(root, res){
        if(root!==null){
            traversal(root.left, res);
            traversal(root.right, res);
            res.push(root.val);
        }
    }
    traversal(root, res);
    return res;
};

时间复杂度:O(n)

空间复杂度:O(n)

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/theajack/leetcode.git
git@gitee.com:theajack/leetcode.git
theajack
leetcode
leetcode
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891