import java.util.ArrayList;
import java.util.Stack;
public class BianryTreeDFS {
/**
* 二叉树的深度优先搜索,递归实现,也就是二叉树的先序遍历
* @param tree 二叉树
*/
public static void preOrderDFS(BinaryTree tree){
if(tree == null){
return;
}
System.out.println(tree.value);
preOrderDFS(tree.left);
preOrderDFS(tree.right);
}
/**
* 二叉树的深度优先搜索,非递归实现
* @param binaryTree 二叉树
*/
public static void preOrderDFS02(BinaryTree binaryTree){
Stack<BinaryTree> stack = new Stack<>();
if(binaryTree != null){
stack.push(binaryTree);
}
BinaryTree node = null;
while(!stack.isEmpty()){
node = stack.pop();
System.out.println(node.value);
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
}
/**
* 二叉树的深度优先搜索,非递归实现使用分治算法
* @param tree 二叉树
*/
public static ArrayList<Integer> preOrderDFS03(BinaryTree tree){
ArrayList<Integer> list =new ArrayList<>();
if(tree == null){
return list;
}
ArrayList<Integer> left = preOrderDFS03(tree.left);
ArrayList<Integer> right = preOrderDFS03(tree.right);
list.add(tree.value);
list.addAll(left);
list.addAll(right);
return list;
}
public static void main(String[] args){
BinaryTree head = new BinaryTree(1);
BinaryTree left = new BinaryTree(2);
BinaryTree right = new BinaryTree(3);
BinaryTree left01 = new BinaryTree(4);
BinaryTree right01 = new BinaryTree(5);
head.left = left;
head.right = right;
left.left = left01;
left.right = right01;
preOrderDFS(head);
System.out.println("-----------");
preOrderDFS02(head);
System.out.println("-----------");
ArrayList<Integer> list = preOrderDFS03(head);
System.out.println(list.toString());
//测试结果[1, 2, 4, 5, 3]
}
}
//二叉树的类
class BinaryTree{
int value;
BinaryTree left;
BinaryTree right;
public BinaryTree(int value){
left = null;
right = null;
this.value = value;
}
}