二叉树的前中后遍历
先序:任何子树的处理顺序都是,先头节点、再左子树、然后右子树
中序:任何子树的处理顺序都是,先左子树、再头节点、然后右子树
后序:任何子树的处理顺序都是,先左子树、再右子树、然后头节点
二叉树的递归遍历
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int v){
value = v;
}
}
public static void order(Node head){
if (head == null){
return;
}
//先序遍历 System.out.println(head.value);
order(head.left);
//中序遍历 System.out.println(head.value);
order(head.right);
//后序遍历 System.out.println(head.value);
}
非递归实现二叉树遍历
1)任何递归函数都可以改成非递归
2)自己设计压栈的来实现
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int v){
value = v;
}
}
//设计一个栈满足弹出的就打印,有右孩子压入栈,在压左孩子 头左右弹出
public static void pre(Node head){
if (head!=null){
Stack<Node> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()){
Node node = stack.pop();
System.out.print(node.value+" ");
if (node.right!=null){
stack.push(node.right);
}
if (node.left!=null){
stack.push(node.left);
}
}
}
System.out.println();
}
//设计一个栈满足整条左边界压入栈,没有左孩子弹出继续压左孩子
public static void in(Node head){
if (head!=null){
Stack<Node> stack = new Stack<>();
stack.push(head);
leftPush(head,stack);
while (!stack.isEmpty()){
Node node1 = stack.pop();
System.out.print(node1.value+" ");
if (node1.right!=null){
stack.push(node1.right);
leftPush(node1.right,stack);
}
}
}
System.out.println();
}
public static void in2(Node cur) {
System.out.print("in-order: ");
if (cur != null) {
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || cur != null) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
} else {
cur = stack.pop();
System.out.print(cur.value + " ");
cur = cur.right;
}
}
}
System.out.println();
}
public static void leftPush(Node node , Stack<Node> stack){
while (node.left!=null){
stack.push(node.left);
node = node.left;
}
}
//设计一个栈满足弹出的就打印,有左孩子压入栈,在压右孩子 头右左弹出进另一个栈弹出就是左右头
public static void post(Node head){
if (head!=null){
Stack<Node> stack = new Stack<>();
Stack<Node> stack1 = new Stack<>();
stack.push(head);
while (!stack.isEmpty()){
Node node = stack.pop();
stack1.push(node);
if (node.left!=null){
stack.push(node.left);
}
if (node.right!=null){
stack.push(node.right);
}
}
while (!stack1.isEmpty()){
System.out.print(stack1.pop().value+" ");
}
}
System.out.println();
}
二叉树的层序遍历
其实就是宽度优先遍历,用队列
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int v) {
value = v;
}
}
public static void level(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);
}
}
}