一:二叉树的存储结构定义
public static class Node {
int val;
Node left;
Node right;
public Node(int val) {
this.val = val;
}
}
二:深度优先遍历
1:先序遍历
递归
public static void pre(Node head){
if (head == null){
return;
}
System.out.println(head.val);
pre(head.left);
pre(head.right);
}
非递归
使用栈来辅助
public static void pre(Node head){
if (head == null){
return;
}
Stack<Node> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()){
head = stack.pop();
System.out.print(head.val + " ");
if (head.right != null){
stack.push(head.right);
}
if (head.left != null){
stack.push(head.left);
}
}
}
2:中序遍历
递归
public static void in(Node head){
if (head == null){
return;
}
in(head.left);
System.out.println(head.val);
in(head.right);
}
非递归
使用栈来辅助
public static void in(Node head){
if (head == null){
return;
}
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.print(head.val + " ");
head = head.right;
}
}
}
3:后序遍历
递归
public static void pos(Node head){
if (head == null){
return;
}
pos(head.left);
pos(head.right);
System.out.println(head.val);
}
非递归
1.使用两个辅助栈
只需要改变先序遍历的进栈方式即可
先序遍历是右孩子先进栈
后序遍历是左孩子先进栈
public static void pos(Node head){
if (head == null){
return;
}
Stack<Node> s1 = new Stack<>();
Stack<Node> s2 = new Stack<>();
s1.push(head);
while (!s1.isEmpty()) {
head = s1.pop(); // 头 右 左
s2.push(head);
if (head.left != null) {
s1.push(head.left);
}
if (head.right != null) {
s1.push(head.right);
}
}
// 左 右 头
while (!s2.isEmpty()) {
System.out.print(s2.pop().val + " ");
}
}
2.只使用一个辅助栈
public static void pos2(Node h) {
System.out.print("pos-order: ");
if (h != null) {
Stack<Node> stack = new Stack<Node>();
stack.push(h);
Node c = null;
while (!stack.isEmpty()) {
c = stack.peek();
if (c.left != null && h != c.left && h != c.right) {
stack.push(c.left);
} else if (c.right != null && h != c.right) {
stack.push(c.right);
} else {
System.out.print(stack.pop().val + " ");
h = c;
}
}
}
}
三:广度优先遍历
public static void level(Node head){
if (head == null){
return;
}
Queue<Node> queue = new LinkedList<>();
queue.add(head);
while (!queue.isEmpty()){
head = queue.poll();
System.out.println(head.val);
if (head.left != null){
queue.add(head.left);
}
if (head.right != null){
queue.add(head.right);
}
}
}