public class Tree {
public class Node{
public Node left;
public Node right;
public int val;
public Node(int val) {
this.val = val;
}
}
//前序递归
public void preOrderRecur(Node head) {
if(head == null) {
return;
}
System.out.println(head.val);
preOrderRecur(head.left);
preOrderRecur(head.right);
}
//中序递归
public void inOrderRecur(Node head) {
if(head == null) {
return;
}
inOrderRecur(head.left);
System.out.println(head.val);
inOrderRecur(head.right);
}
//后序递归
public void postOrderRecur(Node head) {
if(head == null) {
return;
}
postOrderRecur(head.left);
postOrderRecur(head.right);
System.out.println(head.val);
}
//前序非递归,先弹,加右,加左
public void preOrderUnRecur(Node head) {
if(head!=null) {
Stack<Node> stack = new Stack<Node>();
stack.add(head);
while(!stack.isEmpty()) {
head = stack.pop();
if(head.right!=null) {
stack.add(head.right);
}
if(head.left!=null) {
stack.push(head.right);
}
}
}
}
//中序非递归,左 root 右
public void inOrderUnRecur(Node head) {
if(head!=null) {
Stack<Node> stack = new Stack<Node>();
while(!stack.isEmpty()|| head !=null){
if(head !=null) {
stack.push(head);
head = head.left;
}else {
head = stack.pop();
System.out.println(head.val);
head = head.right;
}
}
}
}
//后续非递归 left right root
public void postOrderUnRecur(Node head) {
if(head != null) {
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.add(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()) {
head = s2.pop();
System.out.println(head.val);
}
}
}
}
二叉树的遍历:递归,非递归
最新推荐文章于 2025-06-07 18:58:35 发布