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