树的中序遍历(递归和非递归java实现)
2017-03-13 17:08
204 查看
树的中序遍历(递归和非递归实现)
树的基本遍历是解决树相关问题的基础,所以要很熟悉,理解透彻!
二叉树的结点定义:
中序遍历的递归实现代码:【访问次序:左根右】
中序遍历的非递归算法【java实现】:
树的基本遍历是解决树相关问题的基础,所以要很熟悉,理解透彻!
二叉树的结点定义:
class BinaryTree{ public int value; public BinaryTree leftNode; public BinaryTree rightNode; BinaryTree(int x) { value = x; } }
中序遍历的递归实现代码:【访问次序:左根右】
void InOrder(BinaryTree root){ if(root !=null){ InOrder(root.left); System.out.println(root.value); InOrder(root.right); } }
中序遍历的非递归算法【java实现】:
package com.mytest.mymain; import java.util.Stack; class BTree{ public int value; //public static int value; 那么最终输出都为8个8 public BTree left; public BTree right; BTree(int x) { value = x; } } public class PreOrderwithStack { public static void main(String[] args) { BTree root=new BTree(1); BTree Node2=new BTree(2); BTree Node3=new BTree(3); BTree Node4=new BTree(4); BTree Node5=new BTree(5); BTree Node6=new BTree(6); BTree Node7=new BTree(7); BTree Node8=new BTree(8); root.left=Node2; root.right=Node3; Node2.left=Node4; Node2.right=Node5; Node3.left=Node6; Node3.right=Node7; Node4.left=Node8; preorderfun(root); System.out.println(); inorderfun(root); } public static void inorderfun(BTree root){ Stack<BTree> stack =new Stack<BTree>(); BTree bTree=null; if(root!=null){ bTree=root; while(!stack.isEmpty() || bTree!=null){ while(bTree!=null){//处理所有左结点,进栈 stack.push(bTree); bTree=bTree.left; } if(!stack.isEmpty()){//执行到这里,栈顶元素没有左孩子或者左子树都被访问过 bTree=stack.pop(); System.out.print(bTree.value+" "); bTree=bTree.right; } } } }
相关文章推荐
- java实现的二叉树(前序、中序、后序)递归和非递归遍历,包含层序遍历
- 二叉树的建树、遍历(先序、中序、后序、层次)(递归和非递归)--Java实现
- 二叉树构建以及前中后序遍历(递归和非递归)Java实现
- java实现二叉树的前中后遍历(递归和非递归)
- Java实现二叉树的遍历(递归和非递归)
- 二叉树的遍历(递归与非递归)java实现
- 二叉树前序,中序,后序的递归与非递归的java实现
- 二分查找递归和非递归(java实现)
- java语言实现的二叉树的各种操作(包括递归与非递归遍历二叉树,求二叉树的高度,节点总数,叶子节点等)
- Java 实现快速排序 递归和非递归
- 二叉树的深度(递归和非递归)---java实现
- 我用Java实现的二叉树的遍历(递归和非递归)
- JAVA实现二叉树的前、中、后序遍历(递归与非递归)
- java语言实现二叉树的前序、中序与后序遍历(递归与非递归)
- 递归和非递归两种方式实现二分法查找(java)
- 二叉树的几种遍历递归与非递归java实现
- java实现递归快排和非递归快排
- java实现汉诺塔(递归和非递归)
- 树的后序遍历(递归和非递归java实现)
- java语言实现二叉树的前序、中序与后序遍历(递归与非递归) 层次遍历