preorder,inorder,postorder

2020-07-12  本文已影响0人  Time_Notes

前序遍历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);//根

    }

}

上一篇 下一篇

猜你喜欢

热点阅读