二叉树
二叉树
特殊的二叉树:
二叉查找树:对任意节点,左子节点小于或等于当前节点,右子节点大于或等于当前节点
平衡二叉树:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
最小二叉平衡树的节点的公式如下 F(n)=F(n-1)+F(n-2)+1 这个类似于一个递归的数列,可以参考Fibonacci数列,1是根节点,F(n-1)是左子树的节点数量,F(n-2)是右子树的节点数量。
完满/完整二叉树:所有的叶节点都在树的底部,所有非叶子节点都有2个子节点,所以它就是满二叉树。
注意红黑树和平衡树
突然想到二叉树的非递归后序遍历怎么写,网上找到一篇不错的,自己实现了一下
import java.util.Stack;
public class BinaryTraverse {
public static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; };
boolean visited;
}
public void LRN(TreeNode root){
Stack<TreeNode> stack = new Stack();
TreeNode tmp = root;
while(tmp != null){
stack.push(tmp);
tmp = tmp.left;
}
while(! stack.isEmpty()){
tmp = stack.peek();
if(tmp.visited || tmp.right == null){
stack.pop();
System.out.println(tmp.val);
}
else{
tmp.visited = true;
tmp = tmp.right;
while(tmp != null){
stack.push(tmp);
tmp = tmp.left;
}
}
}
}
public static void main(String args[]){
TreeNode root = new TreeNode(3);
TreeNode left = new TreeNode(4);
TreeNode right = new TreeNode(5);
root.left = left;
root.right = right;
TreeNode l1 = new TreeNode(1);
TreeNode r2 = new TreeNode(6);
left.left = l1;
l1.right = r2;
BinaryTraverse bt = new BinaryTraverse();
bt.LRN(root);
}
}
递归遍历, 非递归前序 中序遍历, 层次遍历
//递归遍历 public void reLNR(TreeNode root){ if(root == null){ return; } TreeNode tmp = root; if(tmp != null){ LNR(tmp.left); System.out.println(tmp.val); LNR(tmp.right); } } //非递归前序遍历 public void NLR(TreeNode root){ Stack<TreeNode> stack = new Stack(); TreeNode tmp = root; stack.push(tmp); while(! stack.isEmpty()){ tmp = stack.peek(); stack.pop(); System.out.println(tmp.val); if(tmp.right != null){ stack.push(tmp.right); } if(tmp.left != null){ stack.push(tmp.left); } } } //非递归中序遍历 public void LNR(TreeNode root){ Stack<TreeNode> stack = new Stack(); TreeNode tmp = root; while(!stack.isEmpty() || tmp != null){ while(tmp != null){ stack.push(tmp); tmp = tmp.left; } if(!stack.isEmpty()){ tmp = stack.peek(); System.out.println(tmp.val); stack.pop(); tmp = tmp.right; } } } //层次遍历 public void LevelTr(TreeNode root){ Queue<TreeNode> queue = new LinkedList(); TreeNode tmp = root; queue.add(tmp); while(! queue.isEmpty()){ tmp = queue.remove(); System.out.println(tmp.val); if(tmp.left != null){ queue.add(tmp.left); } if(tmp.right != null){ queue.add(tmp.right); } } }
浙公网安备 33010602011771号