1. 二叉树的深度优先遍历,使用栈Stack,
DFS(Depth First Search)
function DFS(root){ var stack = []; stack.push(root); var node = null; while(stack.length){ node = stack.pop(); //visit node.data; if(node.right){ stack.push(node.right); } if(node.left){ stack.push(node.left); } } }
2. 二叉树的广度优先遍历,使用队列Queue
BFS(Breadth First Search)
function BFS(root){ var queue = []; queue.push(root); var node = null; while(queue.length){ node = queue.shift(); //visit node.data if(node.left){ queue.push(node.left); } if(node.right){ queue.push(node.right); } } }
时间: 2024-10-29 19:11:06