二叉树的性质
1,二叉树的第i层最多包含2*i-1个节点。
2,二叉树如果深度为k(有k层),那么最多含有(2^k )-1个节点。
3,若二叉树按照从上到下从左到右的方式编号,某节点的编号为k,那么他的左右子树分别编号为2k,2k+1.
4,二叉树分类:满二叉树,完全二叉树,平衡二叉树。
满二叉树:除了叶子结点以外所有的结点都必须满足度最大,即,一个深度为k的满二叉树,其包含的叶子结点数为(2^k )-1。满二叉树即每个非叶子节点的左右子树均在。
完全二叉树:除了深度最大的一层以外,其他每层结点都必须均在,层数为k的完全二叉树的每个节点的编号,与层数为k的满二叉树的结点编号一一对应。
满二叉树必为完全二叉树,完全二叉树不一定为满二叉树。
二叉树的创建:
public static Tree createTree(int [] array){
ArrayList<Tree> list = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
list.add(new Tree(array[i]));
}
Tree root = list.get(0);
for (int i = 0; i < list.size()/2; i++) {
list.get(i).setLeft(list.get(2*i + 1));
if(i*2 + 2 < list.size()){
list.get(i).setRight(list.get(2*i + 2));
}
}
return root;
}
二叉树的遍历:
深度优先,广度优先
前序中序和后序。
深度优先遍历使用栈,广度优先遍历使用队列。
public static void DepthFirstSearch(Tree root){
Stack<Tree> stack = new Stack<>();
stack.push(root);
while(!stack.empty()){
Tree temp = stack.pop();
System.out.println(temp.getVal());
if(temp.getRight() != null){
stack.push(temp.getRight());
}
if(temp.getLeft() != null){
stack.push(temp.getLeft());
}
}
//原树 6 5 4 3 2 1 0
//6 5 3 2 4 1 0
深度优先即先左后右,则在遍历的时候,现将根节点打印之后,将根节点的右子树压入栈中,再将左子树压入栈中。利用栈的性质进行遍历。
广度优先使用队列,先进先出。
public static void breadthFirstSearch(Tree root){
Queue<Tree> queue = new LinkedList<>();
queue.offer(root);
while(queue.size() != 0){
Tree temp = queue.poll(); //取出第一个元素并删除
System.out.print(temp.getVal() + " ");
if(temp.getLeft() != null){
queue.offer(temp.getLeft());
}
if(temp.getRight() != null){
queue.offer(temp.getRight());
}
}
}
先序遍历:根 ->左->右 和深度遍历一致。
中序遍历:左 ->根->右
后序遍历 :左->右->跟
//二叉树中序遍历 左 根 右
public static void inorderTraversal(Tree root){
if(root == null){
return;
}
Stack<Tree> stack = new Stack<Tree>();
Tree p = root;
while(p != null || !stack.empty()){
while(p != null){
stack.push(p);
p = p.getLeft();
}//将该节点压入栈并且其所有左结点都压入
p = stack.pop();
System.out.print(p.getVal() + " ");
p = p.getRight();
}
}
// 二叉树后序遍历
public static void postOrderTraversal(Tree root){
if(root == null){
return;
}
//利用两个栈 对于第一个栈入得顺序是跟左右 入第二个栈的顺序是 跟右左 出栈顺序 左右根
Stack<Tree> stack1 = new Stack<>();
Stack<Tree> stack2 = new Stack<>();
stack1.push(root);
while(!stack1.empty()){
Tree node = stack1.pop();
stack2.push(node);
if(node.getLeft() != null){
stack1.push(node.getLeft());
}
if(node.getRight() != null){
stack1.push(node.getRight());
}
}
while(!stack2.empty()){
System.out.print(stack2.pop().getVal() + " ");
}
}