二叉树的递归遍历,非递归遍历,高度,叶子节点,节点数

package tree;

import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Stack;

import org.omg.CORBA.PUBLIC_MEMBER;

public class BinaryTree {
	public BinaryTreeNode root;
	public BinaryTree(BinaryTreeNode root) {
		super();
		this.root = root;
	}
	public BinaryTree() {		
		this.root = null;
	}
	//递归
	public void preorder() {
		System.out.println("先跟遍历:");
		preorder(root);
	}
	//重载
	private void preorder(BinaryTreeNode p) {
		if (p!=null) {
			System.out.print(p.getData()+" ");
			preorder(p.getLchild());
			preorder(p.getRchild());
		}		
	}
	public void inorder(BinaryTreeNode p) {
		if (p!=null) {			
			inorder(p.getLchild());
			System.out.println(p.getData());
			inorder(p.getRchild());
		}		
	}
	public void postorder(BinaryTreeNode p) {
		if (p!=null) {			
			postorder(p.getLchild());
			postorder(p.getRchild());
			System.out.println(p.getData());
		}		
	}
	public void showleaves(BinaryTreeNode p) {
		if (p!=null) {
		if (p.getLchild()==null&&p.getRchild()==null) {
			System.out.print(p.getData()+" ");
		}
		showleaves(p.getLchild());
		showleaves(p.getRchild());
	}
	}
	public int size() {
		System.out.println("节点数:");
		return size(root);
	}
	private int size(BinaryTreeNode p) {
		if(p==null) {
			return 0;
		}
		int lchildsize=size(p.getLchild());
		int rchildsize=size(p.getRchild());
		return lchildsize+rchildsize+1;
	}
	public int height() {
		System.out.println("高度为:");
		return height(root);
	}
	private int height(BinaryTreeNode p) {
		if (p==null) {
			return 0;			
		}
		int hl=height(p.getLchild());
		int hr=height(p.getRchild());
		return (hl>hr)?hl+1:hr+1;
	}
	//非递归
	public  void pretravel() {
		System.out.println("先序遍历:");
		BinaryTreeNode p=root;
	//	Stack<BinaryTreeNode> mystack = new Stack<BinaryTreeNode>();
		Deque<BinaryTreeNode> myStack = new LinkedList<BinaryTreeNode>();
		if(p!=null) {
			myStack.push(p);
			while(!myStack.isEmpty()) {
				p=myStack.pop();
				System.out.print(p.getData()+" ");
				if (p.getRchild()!=null) {
					myStack.push(p.getRchild());					
				}
				if (p.getLchild()!=null) {
					myStack.push(p.getLchild());					
				}
				
			}		
		}
发布了17 篇原创文章 · 获赞 5 · 访问量 333

猜你喜欢

转载自blog.csdn.net/weixin_45116412/article/details/104926534