这里对先序遍历,中序遍历,后序遍历的递归和非递归写法做一个总结
1. 先序遍历
递归
public static void BSTPreoderTraverse(Node root){
if(root == null){
return;
}
System.out.println(root.value);
BSTPreoderTraverse(root.left);
BSTPreoderTraverse(root.right);
}
非递归
<span style="white-space:pre"> </span>public static void BSTPreoderTraverse1(Node root){
if(root == null){
return;
}
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while(!stack.empty()){
Node current = stack.pop();
System.out.println(current.value);
stack.push(current.right);
stack.push(current.left);
}
}