题目
用递归和非递归两种方法实现二叉树的遍历
实现
前序遍历
递归实现
void preorderRecursive(Node root
{
if(node==null){
return;
}
visit(root);
preorderRecursive(root.left);
preorderRecursive(root.right);
}
非递归实现
借助一个栈实现
void preorderNonrecursive(Node root){
Stack stack=new Stack();
stack.push(root);
while(!stack.isEmpty()){
Node node=stack.pop();
visit(node);
if(node.left!=null)
stack.push(node.left);
if(node.right!=null)
stack.push(node.right);
}
}
中序遍历
递归
void inorderRecursive(Node root
{
if(node==null){
return;
}
inorderRecursive(root.left);
visit(root);
inorderRecursive(root.right);
}
非递归
void inorderNonrecursive(Node root){
Stack s=new Stack();
Node current=root;
while(!s.isEmpty() || current!=null){
if(current!=null)
{
s.push(current);
current=current.left;
}else{
current=s.pop();
visit(current);
current=current.right;
}
}
后序遍历
非递归实现
void postorderNonrecursive(Node root){
Stack s1=new Stack();
Stack s2=new Stack();
s1.push(root);
while(!s1.isEmpty()){
Node node=s1.pop();
s2.push(node);
if(node.left!=null)
s1.push(node.left);
if(node.right!=null)
s1.push(node.right);
}
while(!s2.isEmpty()){
visit(s2.pop());
}
}