[英]recursive and non resursive traversal of tree
通過在二叉搜索樹上執行遞歸和非遞歸預遍歷, 無法得到相同的結果
遞歸方法
public static void preorder(TreeNode root) {
if (root == null)
return;
else {
System.out.print(root);
inorder(root.getLeftPtr());
inorder(root.getRightPtr());
}
}
非遞歸方法
public static void preorder2(TreeNode root){
if(root==null)return;
Stack<TreeNode> stack=new Stack<TreeNode>();
while(true){
while(root!=null){
//process current Node
System.out.print(root);
stack.push(root);
root=root.getLeftPtr();
}
if(stack.isEmpty())break;
root=stack.pop();
root=root.getRightPtr();
}
}
結果
recursive method-> 10-> 5-> 6-> 8-> 12-> 15-> 20
non recursive method-> 10-> 6-> 5-> 8-> 15-> 12-> 20
我認為您的遞歸方法應該是這樣的,
public static void preorder(TreeNode root) {
if (root == null)
return;
else {
System.out.print(root);
preorder(root.getLeftPtr());
preorder(root.getRightPtr());
}
}
這是預排序樹遍歷的非遞歸實現
public void preorderDisplay(Node root) {
Node current = root;
LinkedList<Node> stack = new LinkedList<>();
while (true) {
if (current != null) {
stack.push(current);
System.out.print(current.data + " ");
current = current.left;
} else if (!stack.isEmpty()) {
current = stack.poll();
current = current.right;
} else {
break;
}
}
}
Java中的預排序樹遍歷非遞歸實現:
public static void preTraverseNoRec(Node root){
Stack<Node> stack = new Stack<eNode>();
stack.push(root);
while(stack.size()!=0) {
Node node = stack.pop();
System.out.println(node.data);
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}
}
節點定義為:
public class Node {
int data;
Node left, right, nextRight;
Node(int item)
{
data = item;
left = right = nextRight = null;
}
}
#簡體
public static void preorder(TreeNode root) {
if (root != null) {
System.out.print(root);
preorder(root.getLeftPtr());
preorder(root.getRightPtr());
}
}
http://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.