LeetCode 589,590 N叉树的前后序遍历

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43870742/article/details/102538589

给定一个 N 叉树,返回其节点值的前序,后序遍历

前序Js

/**
 * // Definition for a Node.
 * function Node(val,children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */
/**
 * @param {Node} root
 * @return {number[]}
 */
var preorder = function(root) {
    if (!root){
        return []
    }
    res = [root.val]
    for (i in root.children) {
        res=res.concat(preorder(root.children[i]))
    }
    return res
};

后序Js

/**
 * // Definition for a Node.
 * function Node(val,children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */
/**
 * @param {Node} root
 * @return {number[]}
 */

var postorder = function(root) {
    res = []
    var help = (root) =>{
        if (!root){
            return res
        }
        for (i in root.children) {
            help(root.children[i])
        }
        res.push(root.val)
        return res
    }
    return help(root)
};

猜你喜欢

转载自blog.csdn.net/weixin_43870742/article/details/102538589