public class BinaryTree{
/**
*非递归遍历
*/
//先序遍历,且为根左右
public void preOrder(Node root){
if(root == null)
return;
Stack<Node> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
Node cur = stack.pop();
//先处理根节点
System.out.println(cur.Value);
//后处理左右子节点,由于是根左右的顺序,因此先处理左节点,要先入栈右节点
if(cur.rightChild != null)
stack.push(cur.rightChild);
if(cur.leftChild != null)
stack.push(cur.leftChild);
}
}
//中序遍历,且为左根右
public void midOrder(Node root){
if(root == null)
return;
Stack<Node> stack = new Stack<>();
Node myRoot = root;
while(!stack.isEmpty() || myRoot != null){
if(myRoot != null){
stack.push(myRoot);
myRoot = myRoot.leftChild;
}else{
myRoot = stack.pop();
System.out.println(myRoot.value);
myRoot = myRoot.rightChild;
}
}
}
//后续遍历,且为左右根
//两个栈实现
//栈2保存最后可以直接按顺序输出的值
//栈1作为中间容器,实现栈2按顺序保存树的值
public void posOrder(Node root){
if(root == null)
return;
Stack<Node> stackOne = new Stack<>();
Stack<Node> stackTwo = new Stack<>();
stackOne.push(root);
while(!stackOne.isEmpty()){
Node cur = stackOne.pop();
stackTwo.push(cur);
if(cur.leftChild != null)
stackOne.push(cur.leftChild);
if(cur.rightChild != null)
stackOne.push(cur.rightChild);
}
while(!stackTwo.isEmpty()){
Node cur = stackTwo.pop();
System.out.println(cur.value);
}
}
//一个栈实现后续遍历
//栈中保存一个子树的左子节点和根节点,这样可以先处理左子节点然后通过根节点处理右子节点,最后处理根节点
public void posOrder2(Node root){
if(root == null)
return;
Stack<Node> stack = new Stack<>();
Node curNode = root;
Node lastNode = null;
while(curNode != null){
stack.push(curNode);
curNode = curNode.leftChild;
}
while(!stack.isEmpty()){
curNode = stack.pop();
//有右子树并且右子树不是上一次刚处理过,则不处理当前的根节点,当前根节点需要入栈,要先处理右子树才可以处理当前根节点
//否则可以处理当前根节点
if(curNode.rightChild != null && curNode.rightChild != lastNode){
stack.push(curNode);
curNode = curNode.rightChild;
//因为是处理右子树,故仍需要将该右子树的左节点入栈
while(curNode != null){
stack.push(curNode);
curNode = curNode.leftChild;
}
}else{
//处理当前根节点
System.out.println(curNode.value);
lastNode = curNode;
}
}
}
}
class Node{
public int value;
public Node leftChild;
public Node rightChild;
public Node(int value){
this(value, null, null);
}
public Node(int value, Node leftChild, Node rightChild){
this.value = value;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
}