版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
给定一个 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)
};