二叉树前序遍历(递归)
public static void recursionBefore(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.getValue() + "->");
recursionBefore(root.getLeft());
recursionBefore(root.getRight());
}
二叉树前序遍历(非递归)
public static void beforeTree(TreeNode root){
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
System.out.print("非递归遍历-前序:");
while (!stack.isEmpty()) {
root = stack.pop();
TreeNode left = root.getLeft();
TreeNode right = root.getRight();
System.out.print(root.getValue() + " -> ");
if (right != null) {
stack.push(right);
}
if (left != null) {
stack.push(left);
}
}
System.out.println();
}
二叉树中序遍历(递归)
public static void recursionMiddle(TreeNode root) {
if (root == null) {
return;
}
recursionMiddle(root.getLeft());
System.out.print(root.getValue() + "->");
recursionMiddle(root.getRight());
}
二叉树中序遍历(非递归)
public static void middleTree(TreeNode root){
if (root == null) {
return;
}
System.out.print("非递归遍历-中序:");
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
root = root.getLeft();
} else {
root = stack.pop();
if (root != null) {
System.out.print(root.getValue() + " -> ");
}
root = root.getRight();
}
}
System.out.println();
return;
}
二叉树后序遍历(递归)
public static void recursionAfter(TreeNode root) {
if (root == null) {
return;
}
recursionAfter(root.getLeft());
recursionAfter(root.getRight());
System.out.print(root.getValue() + "->");
}
二叉树后序遍历-2个栈(非递归)
public static void afterTree(TreeNode root) {
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
s1.push(root);
System.out.print("非递归遍历-后序2个栈:");
while (!s1.isEmpty()) {
root = s1.pop();
s2.push(root);
TreeNode left = root.getLeft();
if (left != null) {
s1.push(left);
}
TreeNode right = root.getRight();
if (right != null) {
s1.push(right);
}
}
while (!s2.isEmpty()) {
System.out.print(s2.pop().getValue() + " -> ");
}
System.out.println();
}
二叉树后序遍历-1个栈(非递归)
public static void afterTree2(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
TreeNode tempNode = null;
System.out.print("非递归遍历-后序一个栈:");
while (!stack.isEmpty()) {
tempNode = stack.peek();
TreeNode left = tempNode.getLeft();
TreeNode right = tempNode.getRight();
if (left != null && root != tempNode.getLeft() && root != tempNode.getRight()) {
stack.push(left);
}else if (right != null && root !=tempNode.getRight()) {
stack.push(right);
}else{
System.out.print(stack.pop().getValue() + " -> ");
root = tempNode;
}
}
System.out.println();
}