Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

广度优先遍历(BFS)和深度优先遍历(DFS) #66

Open
kekobin opened this issue Nov 9, 2019 · 0 comments
Open

广度优先遍历(BFS)和深度优先遍历(DFS) #66

kekobin opened this issue Nov 9, 2019 · 0 comments

Comments

@kekobin
Copy link
Owner

kekobin commented Nov 9, 2019

以如下html片段为例,分别说明BFS和DFS的区别。

<div id="app">
	<ul id="ulTest">
		<li class="li-class">
			<p class="li-item-p">this is li item p</p>
		</li>
		<li class="li-class">li item 1</li>
		<li class="li-class">li item 2</li>
		<li class="li-class">li item 3</li>
	</ul>
</div>

DFS

指的是先将当前节点的孩纸节点遍历完,然后再去遍历同级节点,常见的有两种实现方式:

  • (1)递归算法
function deepTraversal(node, nodelist) {
	if(node) {
		nodelist.push(node);

		const { children } = node;

		for(let i=0;i<children.length; i++) {
			// 相当于从最左侧分支遍历,然后中间,最后右边
			deepTraversal(children[i], nodelist)
		}
	}

	return nodelist;
}
  • (2) 非递归算法
function deepTraversal(node) {  
    const nodeList = [];  
    if (node) {  
        const stack = [];  
        stack.push(node);  
        while (stack.length != 0) {  
            const item = stack.pop();  
            nodeList.push(item);  
            const { children } = item;
              
            for (let i = children.length - 1; i >= 0; i--) {
                stack.push(children[i]);
            }  
        }  
    }    
    return nodeList;  
} 

应用于上面的示例如下图所示:
image

结果如下:
image

BFS

指的是先依次遍历兄弟节点,然后遍历兄弟节点下的子节点。

主要使用到了二叉树算法来进行遍历:即先左孩纸,然后右孩纸。

function wideTraversal(node) {
	const nodes = [];

	if(node) {
		const quene = [];
		quene.push(node);

		while(quene.length !== 0) {
			const n = quene.shift()

			nodes.push(n)
			const children = n.children

			for(let i=0;i<children.length;i++) {
				quene.push(children[i])
			}
		}
	}	

	return nodes;
}

上例示例如下:
image

结果如下:
image

@kekobin kekobin changed the title js中的广度优先遍历(BFS)和深度优先遍历(DFS) 广度优先遍历(BFS)和深度优先遍历(DFS) Nov 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant