求二叉树的结点个数(非递归)

package com.my.bitree;

import java.util.Stack;

/*
 * 非递归方法求二叉树的结点个数
 */

public class Node {
	
	private Object data;
	private Node   Lchild;
	private Node  Rchild;
	
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public Node getLchild() {
		return Lchild;
	}
	public void setLchild(Node lchild) {
		Lchild = lchild;
	}
	public Node getRchild() {
		return Rchild;
	}
	public void setRchild(Node rchild) {
		Rchild = rchild;
	}
	
	public int counter(BiTree bt) {
		int count = 0;
		Node root = bt.getRoot();
		Stack<Node> stack = new Stack<Node>();
		if(root != null) {
			stack.push(root);
			while(! stack.isEmpty()) {
				Node node = stack.pop();
				count ++ ;
				if(root.getLchild() != null) {
					stack.push(node.getLchild());
				}
				if(root.getRchild() != null) {
					stack.push(node.getRchild());
				}
			}
		}
		return count;
	}
	
	
	public static void main(String[] args) {
		Node nod = new Node();
		BiTree bt = new BiTree();
		System.out.println(nod.counter(bt));
	}

}
class BiTree{
	private Node root;
	private Node getRoot;
	
	public BiTree() {};
	public Node getRoot() {
		return root;
	}
	public void setRoot(Node root) {
		this.root = root;
	}
	public Node getGetRoot() {
		return getRoot;
	}
	public void setGetRoot(Node getRoot) {
		this.getRoot = getRoot;
	}
	
}

猜你喜欢

转载自blog.csdn.net/hyf_home/article/details/81613072