二叉树遍历(递归和非递归)
一、递归实现二叉树的三种遍历
示例:使用递归实现二叉树的先序, 中序, 后序遍历
public class binaryTree {
void preOrder1(Node root){//先序遍历 根左右
if(root==null)return;
System.out.print(root.Value+" ");
preOrder1(root.left);
preOrder1(root.right);
}
void midOrder1(Node root){//中序遍历 左根右
if(root==null)return;
midOrder1(root.left);
System.out.print(root.Value+" ");
midOrder1(root.right);
}
void postOrder1(Node root){//后序遍历 左右根
if(root==null)return;
postOrder1(root.left);
postOrder1(root.right);
System.out.print(root.Value+" ");
}
}
public class Test {
public static void main(String[] args) {
Node nodeA=new Node("A");
Node nodeB=new Node("B");
Node nodeC=new Node("C");
Node nodeD=new Node("D");
Node nodeE=new Node("E");
Node nodeF=new Node("F");
Node nodeG=new Node("G");
nodeA.left=nodeB;
nodeA.right=nodeC;
nodeB.left=nodeD;
nodeB.right=nodeE;
nodeE.left=nodeG;
nodeC.right=nodeF;
binaryTree binarytree=new binaryTree();
binarytree.preOrder1(nodeA);
System.out.println();
binarytree.midOrder1(nodeA);
System.out.println();
binarytree.postOrder1(nodeA);
二、非递归实现二叉树的遍历
代码如下(示例):运用栈实现二叉树的遍历
public class binaryTree {
void preOrder2(Node root) {//先序遍历 根左右 非递归的方法
//将二叉树放入栈中 先序遍历就是将右孩子先放进去,再放进去左孩子 (先进后出)
if(root==null)return;
Stack<Node> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
Node node=stack.pop();
System.out.print(node.Value);
if(node.right!=null) stack.push(node.right);
if(node.left!=null) stack.push(node.left);
} }
}
void midOrder2(Node root) {//中序遍历 左根右 非递归的方法
//将二叉树放入栈中 中序遍历就是先找到最左节点,最后才放进去右孩子
if(root==null)return;
Stack<Node> stack=new Stack<>();
Node cur=root;
while(!stack.isEmpty()||cur!=null){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
Node node=stack.pop();
System.out.println(node.Value);
if(node.right!=null) cur=node.right;
}
}
void postOrder2(Node root) {//后序遍历 左右根 在先序遍历的基础上改动,之后逆序出栈
if(root==null)return;
Stack<Node> stack=new Stack<>();
Stack<Node> stack2=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
Node node=stack.pop();
stack2.push(node);
if(node.left!=null) stack.push(node.left);
if(node.right!=null) stack.push(node.right);
}
while (!stack2.isEmpty()){
System.out.print(stack2.pop().Value+" ");
}
}
public class Test {
public static void main(String[] args) {
Node nodeA=new Node("A");
Node nodeB=new Node("B");
Node nodeC=new Node("C");
Node nodeD=new Node("D");
Node nodeE=new Node("E");
Node nodeF=new Node("F");
Node nodeG=new Node("G");
nodeA.left=nodeB;
nodeA.right=nodeC;
nodeB.left=nodeD;
nodeB.right=nodeE;
nodeE.left=nodeG;
nodeC.right=nodeF;
binarytree.preOrder2(nodeA);
System.out.println();
binarytree.midOrder2(nodeA);
System.out.println( );
binarytree.postOrder2(nodeA);
}
}