1、二叉树的层次遍历(leetcode 102)
//二叉树的层次遍历
//利用队列
public void FloorVisit(BinaryTree<T> root)
{
Queue<BinaryTree> queue = new LinkedList<BinaryTree>();
if(root==null)
{
return;
}
BinaryTree<T> current;
queue.offer(root);
while(!queue.isEmpty()) {
current = queue.peek();
queue.poll();
System.out.println(current.value);
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}
}
2、求二叉树的节点个数
//求二叉树的节点个数
public int numOfNodes(BinaryTree<T> root)
{
if(root==null)
{
return 0;
}
return (numOfNodes(root.left)+numOfNodes(root.right))+1;
}
//求二叉树的深度
public int depthOfTree(BinaryTree<T> root)
{
if(root==null)
{
return 0;
}
int left = depthOfTree(root.left);
int right = depthOfTree(root.right);
return (left>right?left:right)+1;
}
//求二叉树的宽度
public int widthOfTree(BinaryTree<T> root)
{
if(root==null)
{
return 0;
}
BinaryTree<T> current = root;
Queue<BinaryTree> queue = new LinkedList<BinaryTree>();
queue.offer(root);
int width = 0;
int tempWidth = queue.size();
while(tempWidth>0)
{
if(tempWidth>width)
{
width = tempWidth;
}
while(tempWidth>0)
{
current = queue.peek();
queue.poll();
if(current.left!=null)
{
queue.offer(current.left);
}
if(current.right!=null)
{
queue.offer(current.right);
}
tempWidth--;
}
tempWidth = queue.size();
}
return width;
}
5、判断两个树是否相同
//判断两个树是否相同
public boolean isSameTree(BinaryTree<T> root1,BinaryTree<T> root2)
{
if(root1==null && root2==null)
{
return true;
}
if((root1!=null&&root2==null) || (root1==null && root2!=null))
{
return false;
}
if(root1.value!=root2.value)
{
return false;
}
return (isSameTree(root1.left,root2.left)&&isSameTree(root1.right,root2.right));
}
//二叉树的镜像转换
public void reverseTree(BinaryTree<T> root)
{
if(root==null)
{
return;
}
BinaryTree<T> temp = null;
temp = root.right;
root.right = root.left;
root.left = temp;
//递归调用,把所有的左子树和右子树翻转
reverseTree(root.left);
reverseTree(root.right);
}