二叉树遍历六种方法(含递归和循环)
刷算法题必备基础知识!!!!
//前序遍历(递归)
public static void printTreeFirstRoot(BinaryTreeNode treeRoot){
if(treeRoot == null){
return;
}
System.out.println(treeRoot.getValue());
printTreeFirstRoot(treeRoot.leftNode);
printTreeFirstRoot(treeRoot.rightNode);
}
//中序遍历(递归)
public static void printTreeSecoundRoot(BinaryTreeNode treeRoot){
if(treeRoot == null){
return;
}
printTreeSecoundRoot(treeRoot.leftNode);
System.out.println(treeRoot.getValue());
printTreeSecoundRoot(treeRoot.rightNode);
}
//后续遍历(递归)
public static void printTreeThiredRoot(BinaryTreeNode treeRoot){
if(treeRoot == null){
return;
}
printTreeThiredRoot(treeRoot.leftNode);
printTreeThiredRoot(treeRoot.rightNode);
System.out.println(treeRoot.getValue());
}
//先序遍历(循环)
private static void preOrderTraversal_cir(Node root) {
if (root == null) {
System.out.println("树为空");
return;
}
Stack<Node> stack = new Stack<Node>();
System.out.print("先序遍历:");
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
System.out.print(root.val + " ");
root = root.left;
} else {
root = stack.pop();
root = root.right;
}
}
System.out.println();
}
//中序遍历
private static void inOrderTraversal_cir(Node root) {
if (root == null) {
System.out.println("树为空");
return;
}
Stack<Node> stack = new Stack<Node>();
System.out.print("中序遍历:");
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
System.out.print(root.val + " ");
root = root.right;
}
}
System.out.println();
}
//后序遍历,注意比较难
private static void postOrderTraversal_cir(Node root) {
if (root == null) {
System.out.println("树为空");
return;
}
System.out.print("后序遍历:");
Stack<Node> stack = new Stack<Node>();
Stack<Node> output = new Stack<Node>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
output.push(root);
root=root.right;//先让右子树压栈
}else{
root=stack.pop();
root=root.left;
}
}
while(!output.isEmpty()){
System.out.print(output.pop().val+" ");
}
System.out.println();
}