前序遍历preorder:根左右
var preorder = function(root) {
var res = [];
helper(root,res);
return res;
};
var helper = function(root,res){
if(root){
res.push(root.val); //根
root.children.map(child=>helper(child,res)) //左右
}
}
中序遍历inorder
function inOrder(root,arr=[]){
if(root){
inOrder(root.left,arr)
arr.push(root.val)
inOrder(root.right,arr)
}
return arr;
}
后序遍历postorder:左右根
var postorder = function(root) {
var res = [];
helper(root,res);
return res;
};
var helper = function(root,res){
if(root){
root.children.map(child=>helper(child,res));//左右
res.push(root.val);//根
}
}
网友评论