資料結構之關於樹的操作(樹的遞迴和非遞迴遍曆)-(四補),資料結構遞迴
前面寫了一些關於樹的操作,但是沒有實現樹的遍曆的非遞迴寫法。
通常樹有四種遍曆方法:1.層次遍曆(需要用到樹的高度,此文沒有考慮)
2.前序走訪(根左右);3.中序遍曆(左根右);4.後序遍曆(左右根)
樹的結構如下:
層次遍曆:123456789
前序走訪:124895367
中序遍曆:849251637
後序遍曆:894526731
java代碼實現三種遍曆的遞迴和和非遞迴實現
package com.lip.datastructure.tree;import java.util.Stack;/** * @author lip */public class Tree{public static void main(String[] args){ Node<Integer>root=getNode(); System.out.println("前序走訪(非遞迴)"); preOrder(root); System.out.println("前序走訪(遞迴)"); preOrderRecursive(root); System.out.println(); System.out.println("中序遍曆(非遞迴)"); infixOrder(root); System.out.println("中序遍曆(遞迴)"); infixOrderRecursive(root); System.out.println(); System.out.println("後序遍曆(非遞迴)"); postOrder(root); System.out.println("後序遍曆(遞迴)"); postOrderRecursive(root);}public static Node getNode(){Node<Integer>node1=new Node(1);Node<Integer>node2=new Node(2);Node<Integer>node3=new Node(3);node1.left=node2;node1.right=node3;Node<Integer>node4=new Node(4);Node<Integer>node5=new Node(5);node2.left=node4;node2.right=node5;Node<Integer>node6=new Node(6);Node<Integer>node7=new Node(7);node3.left=node6;node3.right=node7;Node<Integer>node8=new Node(8);Node<Integer>node9=new Node(9);node4.left=node8;node4.right=node9;return node1;}//前序走訪,非遞迴@SuppressWarnings("rawtypes")public static void preOrder(Node root){Stack<Node>stack=new Stack<Node>();stack.push(root);while(stack.size()>0){Node tempNode=stack.pop();if(tempNode!=null){ System.out.print(tempNode.data); stack.push(tempNode.right); stack.push(tempNode.left);}}System.out.println();}//前序走訪(根左右),遞迴public static void preOrderRecursive(Node root){if(root!=null){System.out.print(root.data);preOrderRecursive(root.left);preOrderRecursive(root.right);}}//中序遍曆(左根右),非遞迴public static void infixOrder(Node root){Stack<Node>stack=new Stack<Node>();stack.push(root);while(stack.size()>0){Node temp=stack.pop();if(temp!=null){if((temp.left==null)&&(temp.right==null))System.out.print(temp.data);else{stack.push(temp.right);stack.push(new Node(temp.data));stack.push(temp.left);}}}System.out.println();}//中序遍曆(左根右),遞迴public static void infixOrderRecursive(Node root){if(root!=null){infixOrderRecursive(root.left);System.out.print(root.data);infixOrderRecursive(root.right);}}//後序遍曆(左右根),非遞迴public static void postOrder(Node root){Stack<Node>stack=new Stack<Node>();stack.push(root);Node temp;while(stack.size()>0){temp=stack.pop();if(temp!=null){if(temp.left==null&&temp.right==null)System.out.print(temp.data);else {stack.push(new Node(temp.data));stack.push(temp.right);stack.push(temp.left);}}}System.out.println();}//後序遍曆(左右根),遞迴public static void postOrderRecursive(Node root){if(root!=null){postOrderRecursive(root.left);postOrderRecursive(root.right);System.out.print(root.data);}}} class Node <T> { public Node left; public Node right; public T data; public Node(T data) { this.data=data; } }
其實遞迴和非遞迴的區別也就是非遞迴使用stack來回溯(也可以看做是一種特殊的遞迴)