dfs 与 cfs

135 阅读1分钟

深度优先遍历(Depth-First Search)

3535104753-5c9dea8317820_fix732.png

递归版本

function deepFirstSearch(node,nodeList) {  
    if (node) {    
        nodeList.push(node);    
        var children = node.children;    
        for (var i = 0; i < children.length; i++) 
        //每次递归的时候将 需要遍历的节点 和 节点所存储的数组传下去
        deepFirstSearch(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;
}

广度优先遍历(breadth-first traverse)

89151501-5c9df0b2e4f16_fix732.png

递归版本

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;
}

非递归版本

function breadthFirstSearch(node) {  
    var nodes = [];  
    if (node != null) {  
        var queue = [];  
        queue.unshift(node);  
        while (queue.length != 0) {  
            var item = queue.shift();  
            nodes.push(item);  
            var children = item.children;  
            for (var i = 0; i < children.length; i++)  
                queue.push(children[i]);  
        }  
    }  
    return nodes;  
}

二叉树相关

前序遍历(不使用递归)

preorder(root){
    if(!root){
      return [];
    }
    var result = []
    var stack = [root]
    while(stack.length!==0){
        var top = stack.pop();
        if(top.right){
            stack.push(top.right);
        }
        if(top.left){
            stack.push(top.left);
        }
        result.push(top.element);
    }
    return result;
}

中序遍历(不使用递归)

inorder(root) {
    if(!root){
        return [];
    }
    var result = []
    var stack = []
    while( stack.length !== 0 || root ){
        while(root){
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        result.push(root.element)
        root = root.right;
    }
    return result;
}

后序遍历(不使用递归)

postorder(root) {
    if(!root){
        return [];
    }
    var result = []
    var stack = [root]
    while(stack.length!==0){
        var top = stack.pop();
        result.unshift(top.element);
        if(top.left){
            stack.push(top.left);
        }
        if(top.right){
            stack.push(top.right);
        } 
    }
    return result;
}

最大深度

maxDepth(root) {
    return !root ? 0 : Math.max(this.maxDepth(root.left), this.maxDepth(root.right)) + 1
}