二叉查询树三种遍历的非递归写法

来源:互联网 发布:收音机软件哪个好 编辑:程序博客网 时间:2024/04/30 19:05

这里写出三种儿叉查询树遍历的非递归写法,非常有意思。

preorder:先打印root,再left,最后right。

[java] view plaincopy
  1. public static void BSTPreorderTraverse(Node node) {  
  2.     if (node == null) {  
  3.         return;  
  4.     }  
  5.     Stack<Node> s = new Stack<Node>();  
  6.     s.push(node);  
  7.     while (!s.empty()) {  
  8.         node = s.pop();  
  9.         System.out.println(node.toString());  
  10.         if (node.rightChild != null) {s.push(node.rightChild);}  
  11.         if (node.leftChild != null) {s.push(node.leftChild);}  
  12.     }  
  13. }  

Inorder: 先打印left,再root,最后right.

[java] view plaincopy
  1. public static void BSTInorderTraverse(Node node) {  
  2.     Stack<Node> s = new Stack<Node>();  
  3.     while (!s.empty() || node != null) {  
  4.         if (node != null) {  
  5.             s.push(node);  
  6.             node = node.leftChild;  
  7.         } else {  
  8.             node = s.pop();  
  9.             System.out.println(node.toString());  
  10.             node = node.rightChild;  
  11.         }  
  12.     }  
  13. }  

Postorder: 先打印left,再right,最后root.

[java] view plaincopy
  1. public static void BSTPostorderTraverse(Node node) {  
  2.     if (node == null) {  
  3.         return;  
  4.     }  
  5.     Stack<Node> s = new Stack<Node>();  
  6.       
  7.     Node cur = node;  
  8.       
  9.     while (true) {  
  10.         if (cur != null) {  
  11.             if (cur.rightChild != null) {  
  12.                 s.push(cur.rightChild);  
  13.             }  
  14.               
  15.             s.push(cur);  
  16.             cur = cur.leftChild;  
  17.             continue;  
  18.         }  
  19.           
  20.         if (s.empty()) {  
  21.             return;  
  22.         }  
  23.           
  24.         cur = s.pop();  
  25.         if (cur.rightChild != null && !s.empty() && cur.rightChild == s.peek()) {  
  26.             s.pop();  
  27.             s.push(cur);  
  28.             cur = cur.rightChild;  
  29.         } else {  
  30.             System.out.println(cur.toString());  
  31.             cur = null;  
  32.         }  
  33.           
  34.     }  
  35. }  
[java] view plaincopy
  1. class Node {  
  2.     Node leftChild = null;  
  3.     Node rightChild = null;  
  4.     String name;  
  5.   
  6.     Node(String name) {  
  7.         this.name = name;  
  8.     }  
  9.   
  10.     @Override  
  11.     public String toString() {  
  12.         return name;  
  13.     }  

转自:http://blog.csdn.net/beiyeqingteng/article/details/6725796
原创粉丝点击