import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.junit.Test;
public class BinaryTreeTraverse {
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public void preOrder(TreeNode root) {
if (root != null) {
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
}
public void inOrder(TreeNode root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
}
public void postOrder(TreeNode root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val + " ");
}
}
public void NPreOrder(TreeNode node) {
Stack<TreeNode> stack = new Stack<>();
while (node != null || !stack.isEmpty()) {
if (node != null) {
System.out.print(node.val + " ");
stack.push(node.right);
node = node.left;
} else {
node = stack.pop();
}
}
}
public void NInOrder(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.add(root);
root = root.left;
}
if (!stack.isEmpty()) {
TreeNode tmp = stack.pop();
System.out.print(tmp.val + " ");
root = tmp.right;
}
}
}
public void NPostOrder(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<TreeNode> output = new Stack<TreeNode>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
output.push(root);
stack.push(root);
root = root.right;
} else {
root = stack.pop();
root = root.left;
}
}
while (!output.isEmpty()) {
System.out.print(output.pop().val + " ");
}
}
@Test
public void test() {
TreeNode node1 = new TreeNode(6);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(7);
TreeNode node4 = new TreeNode(3);
TreeNode node5 = new TreeNode(4);
TreeNode node6 = new TreeNode(1);
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
node3.left = node6;
preOrder(node1);
System.out.println();
NPreOrder(node1);
System.out.println("\n");
inOrder(node1);
System.out.println();
NInOrder(node1);
System.out.println("\n");
postOrder(node1);
System.out.println();
NPostOrder(node1);
}
}
忘了在哪学习到的……