我通过在二叉搜索树上执行递归和非递归前序遍历来得不到相同的结果
递归方法
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
答案 0 :(得分:9)
我认为你的递归方法应该是这样的,
public static void preorder(TreeNode root) {
if (root == null)
return;
else {
System.out.print(root);
preorder(root.getLeftPtr());
preorder(root.getRightPtr());
}
}
答案 1 :(得分:0)
Preorder树遍历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;
}
}
答案 2 :(得分:-1)
<强> #Simplified 强>
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/