二叉树相关手写代码题

120 阅读1分钟

二叉树的前中后序遍历

//先序遍历
var preOrder = function (root) {
    const arr = [];
    const order = (root) => {
      if (!root) return;
      arr.push(root.val); // 根
      order(root.left); // 左
      order(root.right); // 右
    };
    order(root);
    return arr;
};

//中序遍历
var inOrder = function (root) {
    const arr = [];
    const order = (root) => {
      if (!root) return;
      order(root.left); // 左
      arr.push(root.val); // 根
      order(root.right); // 右
    };
    order(root);
    return arr;
};

//后序遍历
var lastOrder = function (root) {
    const arr = [];
    const order = (root) => {
      if (!root) return;
      order(root.left); // 左
      order(root.right); // 右
      arr.push(root.val); // 根
    };
    order(root);
    return arr;
};

二叉树的层次遍历

var levelOrder=function(root){
    if(!root) return [];
    let queue=[root];
    let res=[];
    while(queue.length){
        let temp=[];
        let queueLength=queue.length;
        while(queueLength){
            let node=queue.unshift();
            node.left&&queue.push(node.left)
            node.right&&queue.push(node.right)
            queueLength--;
            temp.push(node.val)
        }
        res.push(temp)
    }
    return res;
}

深度优先遍历

function DFS(node,nodeList) {
    if(node!=null){
        nodeList.push(node)
        let children=node.children;
        //每次递归的时候将 需要遍历的节点 和 节点所存储的数组传下去
        for(let i=0;i<children.length;i++){
            DFS(children[i],nodeList)
        }
    }
    return nodeList;
}
//非递归版本
function deepFirstSearch(node) {
    var nodes = [];
    if (node != null) {
        var stack = [];
        stack.push(node);
        while (stack.length != 0) {
        var item = stack.pop();
        nodes.push(item);
        var children = item.children;
        for (var i = children.length - 1; i >= 0; i--)
            stack.push(children[i]);
        }
    }
    return nodes;
}

广度优先遍历

function BFS(node) {
    let nodes=[];
    let stack=[];
    if(node){
        stack.push(node)
        while(stack.length){
            let item=stack.shift()
            nodes.push(item)
            let children=item.children;
            for(let i=0;i<children.length;i++){
                stack.push(children[i])
            }
        }
    }
    return nodes;
}

//递归实现
//递归版本的BFS由于层级太深,会导致堆栈溢出:Maximum call stack size exceeded,但遍历的顺序依旧没有问题,可以在遍历过程中进行操作,不返回遍历数组即可。
function breadthFirstSearch(node) {
    var nodes = [];
    var i = 0;
    if (!(node == null)) {
        nodes.push(node);
        breadthFirstSearch(node.nextElementSibling);
        node = nodes[i++];
        breadthFirstSearch(node.firstElementChild);
    }
    return nodes;
}