Java实现-二叉树先序,中序,后序遍历及递归,非递归遍历

来源:互联网 发布:台州网络答题知识竞赛 编辑:程序博客网 时间:2024/04/30 23:08

对于二叉树的遍历一共存在两种类型:递归遍历和非递归遍历,针对每种类型有分为先序遍历,中序遍历和后序遍历。以下是六种遍历执行过程。

//先序遍历二叉树(递归形式)

public List<Integer> preOrder1(TreeNode root){
if( root != null){
reslist.add(root.val);
System.out.print(root.val+";");
preOrder1(root.leftchild);
preOrder1(root.rightchild);
}
return reslist;
}
//先序遍历二叉树(非递归形式)
public List<Integer> preOrder2(TreeNode root){
Stack<TreeNode> nodestack = new Stack<TreeNode>();
TreeNode node = root;
while(root != null || !nodestack.isEmpty()){
while( root != null ){
//先将根结点添加到顺序表中,然后是打印输出
reslist.add(node.val);
System.out.println(node.val+";");
nodestack.push(node);
node = node.leftchild;
}
//出栈顺序是:先是根结点,其次是左子树结点,最后是右子树结点
node = nodestack.pop();
node = node.rightchild;
}
return reslist;
}

//中序遍历二叉树(递归形式)
public List<Integer> InOrder1(TreeNode root){
if(root != null){
InOrder1(root.leftchild);
reslist.add(root.val);
System.out.print(root.val+";");
InOrder1(root.rightchild);
}
return reslist;
}
//中序遍历二叉树(非递归形式)
public List<Integer> InOrder2(TreeNode root){
Stack<TreeNode> nodestack = new Stack<TreeNode>();
TreeNode node = root;
while( node != null || !nodestack.isEmpty()){
//将结点存入栈中
while( node != null){
nodestack.push(node);
node = node.leftchild;
}
//出栈顺序先是最左端的结点 出栈,接着是根结点出栈,最后是右子树结点
node = nodestack.pop();
//将出栈结点添加到顺序表中,并打印输出
reslist.add(node.val);
System.out.print(node.val+";");
node = node.rightchild;
}
return reslist;
}

//后序遍历二叉树(递归形式)
public List<Integer> PostOrder1(TreeNode root){
if(root != null){
PostOrder1(root.leftchild);
PostOrder1(root.rightchild);
reslist.add(root.val);
System.out.println(root.val+";");
}
return reslist;
}
//后序遍历二叉树(非递归形式)
public List<Integer> PostOrder2(TreeNode root){
Stack<TreeNode> nodestack = new Stack<TreeNode>();
List<Integer> nodelist = new ArrayList<Integer>();
TreeNode node = root;
while( node != null || !nodestack.isEmpty()){
while( node != null || !nodelist.contains(node)){
nodestack.push(node);
node = node.leftchild;
}
if( !nodestack.isEmpty()){
node = nodestack.pop();
reslist.add(node.val);
System.out.print(node.val+";");
if( !nodestack.isEmpty()){
node = nodestack.peek();
node = node.rightchild;
}
}
}
return reslist;

}

说明:对于上述出现的reslist顺序表的定义在上一篇博客中以给出。点击打开链接

0 0
原创粉丝点击