1:前序遍历
(1)访问根结点。
(2)前序遍历左子树。
(3)前序遍历右子树 。
2:中序遍历
(1)中序遍历左子树。
(2)访问根结点。
(3)中序遍历右子树。
3:后序遍历
(1)后序遍历左子树。
(2)后序遍历右子树。
(3)访问根结点。
结点定义:
public class Node {
private int data;
private Node leftNode;
private Node rightNode;
public Node(int data, Node leftNode, Node rightNode){
this.data = data;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public Node getRightNode() {
return rightNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
}
具体实现
public class BinaryTree {
public void printNode(Node node){
System.out.print(node.getData());
}
// 前序遍历
public void frontRecursive(Node root) {
printNode(root);
//遍历左结点
if (root.getLeftNode() != null) {
frontRecursive(root.getLeftNode());
}
//递归遍历右结点
if (root.getRightNode() != null) {
frontRecursive(root.getRightNode());
}
}
//中序遍历
public void midRecursive(Node root) {
if (root.getLeftNode() != null) {
midRecursive(root.getLeftNode());
}
printNode(root);
if (root.getRightNode() != null) {
midRecursive(root.getRightNode());
}
}
//后序遍历
public void backRecursive(Node root) {
if (root.getLeftNode() != null) {
backRecursive(root.getLeftNode());
}
if(root.getRightNode() != null) {
backRecursive(root.getRightNode());
}
printNode(root);
}
/**
* 非递归前序遍历
* */
private void front(Node root) {
if(root == null){
return;
}
Stack<Node> stack = new Stack<Node>();
Node node = root;
while(node != null || !stack.isEmpty()) {
if(node != null) {
printNode(node);
stack.push(node);
node = node.getLeftNode();
} else {
//左子树没了,进入右子树
node = stack.pop().getRightNode();
}
}
}
/**
* 非递归式的中序递归二叉树
*/
private void mid(Node root) {
if(root == null){
return ;
}
Stack<Node> stack = new Stack<Node>();
Node node = root;
while(node != null || !stack.isEmpty()) {
while(node != null) {
stack.push(node);
node = node.getLeftNode();
}
if(!stack.isEmpty()) {
node = stack.pop();
printNode(node);
//进入右子树
node = node.getRightNode();
}
}
}
/**
* 非递归的后序遍历二叉树
* 后序遍历的关键就是要判断上一个结点的右结点访问了没,所以要记录上次访问的结点
*/
private void back(Node root) {
if(root == null){
return;
}
Stack<Node> stack = new Stack<Node>();
Node node = root;
Node lastVisit = null;
while(node != null || !stack.isEmpty()) {
while(node != null) {
stack.push(node);
node = node.getLeftNode();
}
while(!stack.isEmpty()) {
node = stack.peek();
if(node.getRightNode() == null || node.getRightNode() == lastVisit) {
printNode(node);
lastVisit = node;
stack.pop();
if(stack.isEmpty()){
return;
}
} else {
node = node.getRightNode();
break;
}
}
}
}
}