public void getLeaves(){
System.out.print("叶子节点为:");
getLeaves(root);
}
private void getLeaves(BinaryNode p){
if(p!=null)
{
if(p.left==null&&p.right==null){
System.out.print(p.data.toString()+"");
t++;
}
getLeaves(p.left);
getLeaves(p.right);
}
}
// 构造一棵二叉树
public void getBinaryTree(String[] nodes) {
this.root = (BinaryNode) getBinaryTreeByPreOrder(nodes);
}
private int i = 0;
private BinaryNode getBinaryTreeByPreOrder(String[] nodes) {
BinaryNode node = null;
if (i < nodes.length) {
String tmp = nodes;
i++;
if (tmp != null) {
node = new BinaryNode(tmp);
// System.out.println("头结点"+node);
node.left = (BinaryNode) getBinaryTreeByPreOrder(nodes);
//System.out.println("左孩子" + node.left);
node.right = (BinaryNode) getBinaryTreeByPreOrder(nodes);
//System.out.println("右孩子" + node.right);
}
}
return node;
}
public static void main(String[] args) {
String[] nodes = { "A", "B", "D", null, "G",null,null,null, "C","E", null,null, "F", "H",null,
null, null };
BinaryTree bt = new BinaryTree();
bt.getBinaryTree(nodes);
bt.getLeaves(); |