590. N 叉树的后序遍历 | Javascript 递归实现

题目

题目链接:590. N 叉树的后序遍历

解题思路

递归后续遍历,正常的思路
然后有一个要注意的地方就是如果js定义了全局变量来存储结果,每次调用函数之前一定要记得清空,否则答案会带上之前的结果。

代码

/**
 * // Definition for a Node.
 * function Node(val,children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */
let result = [];  // 结果数组

function postN(root) {
    if (root) {
        for (let item of root.children) {
            // console.log(item);
            if (item.children.length > 0) postN(item);
            else result.push(item.val);
        }
        result.push(root.val);
    }
}

/**
 * @param {Node|null} root
 * @return {number[]}
 */
var postorder = function(root) {
    result = [];
    postN(root);
    return result;
};
posted @ 2022-03-12 23:36  azoux  阅读(46)  评论(0编辑  收藏  举报