import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
//先序遍历
public static ArrayList<Integer> preOrder(TreeNode root)
{
ArrayList<Integer> list = new ArrayList<Integer>();
if(root == null) return null;
list.add(root.val);
if(root.left!=null) list.addAll(preOrder(root.left));
if(root.right!=null) list.addAll(preOrder(root.right));
return list;
}
//中序遍历
public static ArrayList<Integer> inOrder(TreeNode root)
{
ArrayList<Integer> list = new ArrayList<Integer>();
if(root == null) return null;
if(root.left!=null) list.addAll(inOrder(root.left));
list.add(root.val);
if(root.right!=null) list.addAll(inOrder(root.right));
return list;
}
//后序遍历
public static ArrayList<Integer> postOrder(TreeNode root)
{
ArrayList<Integer> list = new ArrayList<Integer>();
if(root == null) return null;
if(root.left!=null) list.addAll(postOrder(root.left));
if(root.right!=null) list.addAll(postOrder(root.right));
list.add(root.val);
return list;
}
//广度优先遍历
public static ArrayList<Integer> levelTraverse(TreeNode root) {
if (root == null) {
return null;
}
ArrayList<Integer> list = new ArrayList<Integer>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return list;
}
//深度优先遍历
public static ArrayList<Integer> DFSTraverse(TreeNode root) {
if (root == null) {
return null;
}
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack= new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
list.add(node.val);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return list;
}
public static void main(String[] args)
{
TreeNode one = new TreeNode(1);
TreeNode two = new TreeNode(2);
TreeNode three = new TreeNode(3);
TreeNode four = new TreeNode(4);
TreeNode five = new TreeNode(5);
one.left = three;
one.right = five;
five.left = two;
five.right = four;
// ArrayList<Integer> list = TreeNode.levelTraverse(one);
// ArrayList<Integer> list = TreeNode.preOrder(one);
// ArrayList<Integer> list = TreeNode.inOrder(one);
// ArrayList<Integer> list = TreeNode.postOrder(one);
ArrayList<Integer> list = TreeNode.DFSTraverse(one);
Iterator<Integer> it = list.iterator();
while(it.hasNext())
{
System.out.print(it.next());
}
}
}