public class TNode {// 二叉树结点类
public Object val; // 结点值
public TNode lChild;// 左结点
public TNode rChild;// 右结点
}
public TNode(Object val) {
this.val = val;
}
1.数组构建二叉树
public TNode createBiTree(Object... values) {
if (values == null || values.length == 0) {
return null;
}
return createBiTree(values, 0);
}
private TNode createBiTree(Object[] values, int index) {
TNode root = null;
if (index < values.length) {
if (values[index] == null) {
return null;
}
root = new TNode(values[index]);
root.lChild = createBiTree(values, 2 * index + 1);
root.rChild = createBiTree(values, 2 * index + 2);
}
return root;
}
例如:用数组{1,2,3,null,4,null,5}构建的二叉树是这样的:
2.二叉树的遍历
public void preOrder(TNode root) {// 非递归先序遍历
if (root == null) {
return;
}
Stack<TNode> s = new Stack<TNode>();
while (true) {
while (root != null) {
System.out.println(root.val);
s.push(root);
root = root.lChild;
}
if (s.isEmpty()) {
break;
}
root = s.pop().rChild;
}
}
public void inOrder(TNode root) {// 非递归中序遍历
if (root == null) {
return;
}
Stack<TNode> s = new Stack<TNode>();
while (true) {
while (root != null) {
s.push(root);
root = root.lChild;
}
if (s.isEmpty()) {
break;
}
root = s.pop();
System.out.println(root.val);
root = root.rChild;
}
}
public void postOrder(TNode root) {// 非递归后序遍历
if (root == null) {
return;
}
Stack<TNode> s = new Stack<TNode>();
Stack<Integer> s2 = new Stack<Integer>();
Integer i = new Integer(1);
while (root != null || !s.isEmpty()) {
while (root != null) {
s.push(root);
s2.push(0);
root = root.lChild;
}
while (!s.empty() && s2.peek().equals(i)) {
s2.pop();
System.out.println(s.pop().val);
}
if (!s.empty()) {
s2.pop();
s2.push(i);
root = s.peek().rChild;
}
}
}
public void levOrder(TNode root) {// 层次遍历
if (root == null) {
return;
}
LinkedList<TNode> q = new LinkedList<TNode>();
q.addLast(root);
while (!q.isEmpty()) {
TNode out = q.removeFirst();
System.out.println(out.val);
if (out.lChild != null) {
q.addLast(out.lChild);
}
if (out.rChild != null) {
q.addLast(out.rChild);
}
}
}
3.求第k层的节点数
public getNodeNumOfK(TNode root,int k) {
if(root == null || k<=0) return 0;
if(k == 1) return 1;
k--;
return getNodeNumOfK(root.lChild,k)+getNodeNumOfK(root.rChild,k);
}