中序遍历是 左--》中--》右的顺序,可以考虑先找到所有左节点,然后按照先进后出栈的结构来实现。
先来一个简单的二叉树。
public class BinarySearchTree {
Node root;
public void add(Integer value){
if(root == null){
root = new Node(value);
return;
}
Node parent = root;
Node current = root;
while(current != null){
if(current.value == value){
return;
}
parent = current;
if(current.value < value){
current = current.right;
}else if(current.value > value){
current = current.left;
}
}
if(parent.value > value){
parent.left = new Node(value);
}else {
parent.right = new Node(value);
}
}
public static class Node{
Node left;
Node right;
Integer value;
public Node(Integer value) {
this.value = value;
}
}
}
再来实现非递归的中序遍历
public class BinaryTreeTraverse {
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
bst.add(3);
bst.add(5);
bst.add(1);
bst.add(8);
bst.add(4);
bst.add(6);
bst.add(7);
inOrderTraverse(bst);
}
public static void inOrderTraverse(BinarySearchTree bst){
Stack<BinarySearchTree.Node> stack = new Stack<>();
BinarySearchTree.Node temp = bst.root;
while(!stack.isEmpty() || temp != null){
while(temp != null){
stack.add(temp);
temp = temp.left;
}
BinarySearchTree.Node pop = stack.pop();
System.out.println(pop.value);
temp = pop.right;
}
}
}