前端算法之遍历二叉树

背景:二叉树是一种数据结构,那么如果使用js遍历它呢

1、前序遍历,根--左--右

const frontTree = (tree) => {

 let rs = [];
 let trase = (vtree) => {
        if(!vtree) {
            return 'ooo';
        }

        rs.push(vtree.value);
        rs.push(trase(vtree.left))
        rs.push(trase(vtree.right))
    }
 trase(tree)
    
    return rs;
}

2、中序遍历,左--根--右

const middleTree = (tree) => {

 let rs = [];
 let trase = (vtree) => {
        if(!vtree) {
            return 'ooo';
        }

        rs.push(trase(vtree.left))
        rs.push(vtree.value);
        rs.push(trase(vtree.right))
    }
 trase(tree)
    
    return rs;
}

3、后序遍历,左--右--根

const endTree = (tree) => {

 let rs = [];
 let trase = (vtree) => {
        if(!vtree) {
            return 'ooo';
        }

        rs.push(trase(vtree.left))
        rs.push(trase(vtree.right))
        rs.push(vtree.value);
    }
 trase(tree)
    
    return rs;
}

4、js的二叉数结构

const vTree = {
    value: 1,
    left: {
        value: 2,
        left: {
            value: 3,
            left: {value: 4},
            right: {value: 5},
        },
        right: {
            value: 6,
            left: {value: 7},
            right: {value: 8},
        }
    },
    right: {
        value: 9,
        left: {value: 10},
        right: {value: 11}
    }
}

执行

console.log(frontTree(vTree));
console.log(middleTree(vTree));
console.log(endTree(vTree));

结果是:

你可能感兴趣的:(javascript,算法-数据结构)