在此内容之上增加了中序遍历二叉树的非递归的两种实现、线序遍历统计二叉树的叶子数、二叉树的深度
//中序遍历二叉树非递归
public void InOrderTraverse(BinaryNode<T> node){
Stack<BinaryNode> stack=new Stack<BinaryNode>();
if(node!=null)
stack.add(node);
while(!stack.isEmpty()){
while(stack.peek()!=null){
node=stack.peek().left;
stack.push(node);
}
stack.pop();
if(!stack.isEmpty()){
node=stack.pop();
System.out.print(node.data+" ");
stack.push(node.right);
}
}
}
//中序遍历二叉树非递归
public void InOrderTraverse2(BinaryNode<T> node){
Stack<BinaryNode> stack=new Stack<BinaryNode>();
BinaryNode<T> p=node;
while(p!=null || !stack.isEmpty()){
if(p!=null){
p=stack.push(p);
p=p.left;
}else{
p=stack.pop();
System.out.print(p.data+" ");
p=p.right;
}
}
}
int count=0;
//先序遍历统计二叉树中的叶子节点
public int countLeaf(BinaryNode<T> node){
if(node!=null){
if(node.left==null&&node.right==null)
count++;
countLeaf(node.left);
countLeaf(node.right);
}
return count;
}
//统计二叉树的深度
public int treeDepth(BinaryNode<T> node){
int depthral=0;
int depthLeft=0;
int depthRight=0;
if(node==null)
depthral=0;
else{
depthLeft=treeDepth(node.left);
depthRight=treeDepth(node.right);
depthral=1+(depthLeft>depthRight? depthLeft:depthRight);
}
return depthral;
}