二叉树节点结构
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value=data;
}
}
用递归方式实现二叉树的先序、中序、后序遍历
先序遍历(头左右):
public static void f(Node head){
if (head==null){
return;
}else{
System.out.println(head.value+" ");
f(head.left);
f(head.right);
}
}
中序遍历(左头右):
public static void f(Node head){
if (head==null){
return;
}else{
f(head.left);
System.out.println(head.value+" ");
f(head.right);
}
}
后序遍历(左右头):
public static void f(Node head){
if (head==null){
return;
}else{
f(head.left);
f(head.right);
System.out.println(head.value+" ");
}
}
重点:非递归做法
准备一个栈
1)从栈中弹出一个节点car
2)打印car
3)先压右在压左
4)周而复始
public static void preOrderUnRecur(Node head) {
System.out.println("pre-order: ");
if (head != null) {
Stack<Node> stack = new Stack<>();
stack.add(head); //先把头节点压到栈里面去
while (!stack.isEmpty()) {
head = stack.pop();
System.out.println(head.value + " ");
if (head.right != null) {
stack.push(head.right); //右边如果不等于空 压右
}
if (head.left != null) {
stack.push(head.left); //左边如果不等于空 压左
}
}
}
System.out.println();
}
后序遍历:
1)准备两个栈
2)弹 car
3)car 放入收集栈里面
4)先压左在压右
public static void posOrderUnRecur1(Node head){
System.out.println("pos-order: ");
if (head!=null){
Stack<Node> s1 = new Stack<>();
Stack<Node> s2 = new Stack<>();
s1.push(head); //先把头节点压入栈1里面去
while (!s1.isEmpty()){
head=s1.pop(); //每一次弹出一个 弹出的就把他放入到s2里面去
s2.push(head);
if (head.left!=null){
s1.push(head.left); //先压左
}
if (head.right!=null){
s2.push(head.right); //后压右
}
}
while (!s2.isEmpty()){
System.out.println(s2.pop().value+" "); //收集完后单独从收集栈里面打印
}
}
System.out.println();
}
中序遍历
准备一个栈
整棵树左边界进栈
依次弹出节点的过程中打印
对弹出节点的右树周而复始
public static void inOrderUnRecur(Node head){
System.out.println("in-order: ");
if (head!=null){
Stack<Node> stack = new Stack<>();
while (!stack.isEmpty()||head!=null){
if (head!=null){
stack.push(head);
head=head.left; //不停的把左边界进栈
}else{
head=stack.pop(); //弹出就打印
System.out.println(head.value+ " ");
head=head.right; //head到它的右树上面去
}
}
}
System.out.println();
}
如何完成二叉树的宽度优先遍历
public static void w(Node head){
if (head==null){
return;
}
Queue<Node> queue = new LinkedList<>();
queue.add(head);
while (!queue.isEmpty()){
Node cur = queue.poll();
System.out.println(cur.value);
if (cur.left!=null){
queue.add(cur.left);
}
if (cur.right!=null){
queue.add(cur.right);
}
}
}