这里的树通常是指二叉树。
class
TreeNode{
int
value;
TreeNode left;
TreeNode right;
}
public class TreeNode {
public static void main(String[] args) {
Tree A = new Tree("A");
Tree B = new Tree("B");
Tree C = new Tree("C");
Tree D = new Tree("D");
Tree E = new Tree("E");
Tree F = new Tree("F");
Tree G = new Tree("G");
Tree H = new Tree("H");
Tree I = new Tree("I");
Tree J = new Tree("J");
Tree K = new Tree("K");
A.left = B;
A.right = C;
B.left = D;
B.right = E;
C.left = F;
C.right = G;
D.left = H;
D.right = I;
E.left = J;
E.right = K;
// 先序遍历
// A,B,D,H,I,E,J,K,C,F,G
/*
* ArrayList<String> list = new ArrayList<String>(); Stack<Tree> mStack
* = new Stack<Tree>(); mStack.push(A); while(mStack.size()!=0){ Tree p
* = mStack.pop(); list.add(p.value);
*
* if(p.right!=null){ mStack.push(p.right); }
*
* if(p.left!=null){ mStack.push(p.left); } }
*/
// 中序遍历
// H,D,I,B,J,E,K,A,F,C,G
ArrayList<String> list = new ArrayList<String>();
Stack<Tree> mStack = new Stack<Tree>();
/*Tree p = A;
while (mStack.size() != 0 || p != null) {
if (p != null) {
mStack.push(p);
p = p.left;
} else {
Tree t = mStack.pop();
list.add(t.value);
p = t.right;
}
}*/
// 后序遍历
// H,I,D,J,K,E,B,F,G,C,A
mStack.push(A);
Tree prev = null;
while(!mStack.empty()){
Tree tmp = mStack.peek();
if(prev == null ||prev.left == tmp ||prev.right == tmp){
if(tmp.left!= null){
mStack.push(tmp.left);
}else if(tmp.right != null){
mStack.push(tmp.right);
}else {
mStack.pop();
list.add(tmp.value);
}
}else if(tmp.left == prev){
if(tmp.right != null){
mStack.push(tmp.right);
}else{
mStack.pop();
list.add(tmp.value);
}
}else if(tmp.right == prev){
mStack.pop();
list.add(tmp.value);
}
prev = tmp;
}
for (String str : list) {
System.out.print(str + ",");
}
}
}
class Tree {
String value;
Tree left;
Tree right;
Tree(String x) {
this.value = x;
this.left = null;
this.right = null;
}
}
下面是一些与二叉树有关的概念:
二叉树搜索: 对于所有节点,顺序是:left children <= current node <= right children;
平衡vs.非平衡: 它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树;
满二叉树: 除最后一层无任何子节点外,每一层上的所有结点都有两个子结点;
完美二叉树(Perfect Binary Tree): 一个满二叉树,所有叶子都在同一个深度或同一级,并且每个父节点都有两个子节点;
完全二叉树: 若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。
二叉树搜索: 对于所有节点,顺序是:left children <= current node <= right children;
平衡vs.非平衡: 它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树;
满二叉树: 除最后一层无任何子节点外,每一层上的所有结点都有两个子结点;
完美二叉树(Perfect Binary Tree): 一个满二叉树,所有叶子都在同一个深度或同一级,并且每个父节点都有两个子节点;
完全二叉树: 若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。