二叉树的递归遍历与非递归遍历

首先创建二叉树存储数据对象

 

package com.tree;

public class TreeData {

	private String data;
	
	public TreeData(){}
	
	public TreeData(String data){
		this.data = data;
	} 

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public String toString() {		
		return this.data;
	}
	
	
}

  然后创建二叉树对象

 

package com.tree;

public class TreeVo {

	private TreeData data;
	private TreeVo leftChild;
	private TreeVo rightChild;
	
	public TreeVo(){} 
	
	public TreeVo(TreeData data){
		this.data = data;
	}
	
	public TreeVo(TreeData data,TreeVo leftChild,TreeVo rightChild){
		this.data = data;
		this.leftChild = leftChild;
		this.rightChild = rightChild;
	}

	public TreeData getData() {
		return data;
	}

	public void setData(TreeData data) {
		this.data = data;
	}

	public TreeVo getLeftChild() {
		return leftChild;
	}

	public void setLeftChild(TreeVo leftChild) {
		this.leftChild = leftChild;
	}

	public TreeVo getRightChild() {
		return rightChild;
	}

	public void setRightChild(TreeVo rightChild) {
		this.rightChild = rightChild;
	}
}

  最后 构建数与遍历

package com.tree;

import java.util.Stack;

public class BuildTree {

	public static void main(String[] args) {
		
		//创建叶子节点
		TreeVo ele1 = new TreeVo(new TreeData("叶子节点1"));
		TreeVo ele2 = new TreeVo(new TreeData("叶子节点2"));
		TreeVo ele3 = new TreeVo(new TreeData("叶子节点3"));
		TreeVo ele4 = new TreeVo(new TreeData("叶子节点4"));
		TreeVo ele5 = new TreeVo(new TreeData("叶子节点5"));
		TreeVo ele6 = new TreeVo(new TreeData("叶子节点6"));
		TreeVo ele7 = new TreeVo(new TreeData("叶子节点7"));
		TreeVo ele8 = new TreeVo(new TreeData("叶子节点8"));
 
		//创建中间节点
		TreeVo ele9 = new TreeVo(new TreeData("中间节点1"),ele1,ele2);
		TreeVo ele10 = new TreeVo(new TreeData("中间节点2"),ele3,ele4);
		TreeVo ele11 = new TreeVo(new TreeData("中间节点3"),ele5,ele6);
		TreeVo ele12 = new TreeVo(new TreeData("中间节点4"),ele7,ele8);
		
		//创建根节点
		TreeVo ele13 = new TreeVo(new TreeData("根节点1"),ele9,ele10);
		TreeVo ele14 = new TreeVo(new TreeData("根节点2"),ele11,ele12);
		
		TreeVo ele15 = new TreeVo(new TreeData("根节点"),ele13,ele14);
		
		stackData(ele15);
	}
	
	//递归遍历
	public static  void showData(TreeVo tree){
		if(tree.getLeftChild() != null){
			showData(tree.getLeftChild());
		}
		System.out.println(tree.getData().toString());
		if(tree.getRightChild() != null){
			showData(tree.getRightChild());
		}
	}
	
	//非递归遍历
	public static void stackData(TreeVo tree){
		Stack stack = new Stack();
		stack.push(tree);
		while(!stack.isEmpty()){
			TreeVo treeVo = (TreeVo)stack.pop();
			System.out.println(treeVo.getData().toString());
			if(treeVo.getRightChild() != null){
				stack.push(treeVo.getRightChild());
			}
			for( TreeVo t = treeVo.getLeftChild();t!=null;t = t.getLeftChild()){
				System.out.println(t.getData().toString());
				if(t.getRightChild() != null){
					stack.push(t.getRightChild());
				}
			}
		}
	}
}

  

 

你可能感兴趣的:(二叉树的递归遍历与非递归遍历)