## Title Description

Order to achieve the first binary tree, in sequence, after traversal, comprising recursively and non-recursively

## achieve

### Recursively

``````public static class Node {
int val;
Node left;
Node right;

public Node(int data) {
this.val = data;
}

}

// 前序递归
public static void preTraversal(Node head) {

}

// 中序递归
public static void inTraversal(Node head) {
}

// 后序递归
public static void posTraversal(Node head) {

}

``````

### A non-recursively

#### prologue

Use the stack structure to achieve, attention to be pressed push the right child, the right child after such a stack order.

`````` // 前序非递归
public static void preTravelsal1(Node head) {

Stack<Node> stack = new Stack<>();
while (!stack.isEmpty()) {
}
}
``````

#### In order

It is implemented using a stack structure.

• The current node is not empty, pushed onto the stack, the current node is left child
• The current node is empty, a take from the stack, the current node is the right child
``````// 中序非递归
public static void inTravelsal1(Node head) {

Stack<Node> stack = new Stack<>();
while (!stack.isEmpty() || head != null) {
} else {
}
}
}
``````

#### After the order

Preorder traversal around the root, root around postorder traversal.
So in a non-recursive version it is very easy to order around the root, root into the left and right order. Then place each time before a preorder traversal of the print output, the current to the second node into the stack: the root right and left.
Finally, the data of the second stack to a pop-up time, which is about the order of the root

``````// 后序非递归

Stack<Node> s1 = new Stack<>();
Stack<Node> s2 = new Stack<>();
while(!s1.isEmpty()){
}
while(!s2.isEmpty()){
System.out.print(s2.pop().val + " ");
}
}
``````
Published 89 original articles · won praise 13 · views 20000 +

### Guess you like

Origin blog.csdn.net/Dawn510/article/details/105258652
Recommended
Ranking
Daily