二叉树的先序中序后序遍历
package Sort; import java.util.Arrays; import java.util.ArrayList; import java.util.Stack; public class BubbleSort { public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public void preTraversal(TreeNode proot) { ArrayList<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode node = proot; while(node!=null || !stack.isEmpty()) { if(node!=null) { list.add(node.val); stack.push(node); node = node.left; } else { node = stack.pop(); node = node.left; } } } public void InTTraversal(TreeNode proot) { Stack<TreeNode>stack = new Stack<TreeNode>(); ArrayList<Integer> list = new ArrayList<Integer>(); TreeNode node = proot; while(node!=null || !stack.isEmpty()) { if(node!=null) { stack.push(node); node = node.left; } else { node = stack.pop(); list.add(node.val); node = node.right; } } } public void postTraversal(TreeNode proot) { ArrayList<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); Stack<TreeNode>output = new Stack<TreeNode>();//构造一个中间栈来存储逆后序遍历的结果 TreeNode node =proot; while(node!=null || !stack.isEmpty()) { if(node!=null) { stack.push(node); output.push(node); node = node.right; } else{ node = stack.pop(); node = node.left; } } while(!output.isEmpty()) { list.add(output.pop().val); } } public void theFirstTraversal(TreeNode root) { //先序遍历 ArrayList<Integer> list = new ArrayList<Integer>(); list.add(root.val); if (root.left != null) { //使用递归进行遍历左孩子 theFirstTraversal(root.left); } if (root.right != null) { //递归遍历右孩子 theFirstTraversal(root.right); } } public void INTraversal(TreeNode root) { //先序遍历 ArrayList<Integer> list = new ArrayList<Integer>(); if (root.left != null) { //使用递归进行遍历左孩子 INTraversal(root.left); } list.add(root.val); if (root.right != null) { //递归遍历右孩子 INTraversal(root.right); } } public void PostTraversal(TreeNode root) { //先序遍历 ArrayList<Integer> list = new ArrayList<Integer>(); if (root.left != null) { //使用递归进行遍历左孩子 theFirstTraversal(root.left); } if (root.right != null) { //递归遍历右孩子 theFirstTraversal(root.right); } list.add(root.val); } }