深度遍历,即尽可能往树的纵深的方向搜索,所以优先深入遍历树的左节点,直至叶子节点,再往回遍历已遍历的节点的右节点。使用栈来实现
package com.practice;
import java.util.LinkedList;
public class DepthFirstSearch {
public static TreeNode createTree(int[] arr, int i) {
TreeNode root = null;
if(i<arr.length) {
root = new TreeNode(arr[i]);
root.left = createTree(arr, 2*i+1);
root.right = createTree(arr, 2*i+2);
}
return root;
}
public static void search(int[] arr) {
TreeNode root = createTree(arr, 0);
if(root==null) return;
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.add(root);
while(!list.isEmpty()) {
TreeNode node = list.pop();
System.out.print(node.val+",");
if(node.right!=null) list.push(node.right);
if(node.left!=null) list.push(node.left);
}
}
public static void main(String[] args) {
int[] arr = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };
search(arr);
}
}
广度优先遍历,即层序遍历,优先将根节点遍历完,再遍历根节点的子节点。使用队列来实现
package com.practice;
import java.util.LinkedList;
import java.util.Queue;
public class WidthFirstSearch {
public static TreeNode createTree(int[] arr, int i) {
TreeNode root = null;
if(i<arr.length) {
root = new TreeNode(arr[i]);
root.left = createTree(arr, 2*i+1);
root.right = createTree(arr, 2*i+2);
}
return root;
}
public static void search(int[] arr) {
TreeNode root = createTree(arr, 0);
if(root==null) return;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
for(int i=0;i<size;i++) {
TreeNode node = queue.poll();
System.out.print(node.val+",");
if(node.left!=null) queue.add(node.left);
if(node.right!=null) queue.add(node.right);
}
}
}
public static void main(String[] args) {
int[] arr = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };
search(arr);
}
}