0.基本概念
public class TreeNode<T> {
T data;
TreeNode firstson;
TreeNode nextbrother;
public TreeNode(T x) {
this.data = x;
}
}
- 树的先序遍历 = 对应二叉树的先序遍历
- 树的后序遍历 = 对应二叉树的中序遍历
- 给定树的先序+后序序列,可以唯一确定一棵树
- 树的某个结点 p 是叶子结点,则满足
p->firstson == null
1.树的统计问题
树的叶子结点数
public int leafCount(TreeNode root) {
if (root == null)
return 0;
if (root.firstson == null)
return 1 + leafCount(root.nextbrother);
return leafCount(root.firstson) + leafCount(root.nextbrother);
}
树的高度
public int height(TreeNode root) {
if (root == null)
return 0;
return Math.max(1 + height(root.firstson), height(root.nextbrother));
}
2.输出树的结点
输出所有结点及其层次
public void preOrder(TreeNode root, int level) {
if (root == null)
return;
System.out.println(root.data + "," + level);
preOrder(root.firstson, level + 1);
preOrder(root.nextbrother, level);
}
输出所有叶子结点 ★
public void printLeaf(TreeNode root) {
if (root == null)
return;
if (root.firstson == null)
System.out.println(root.data);
printLeaf(root.nextbrother);
} else {
printLeaf(root.firstson);
printLeaf(root.nextbrother);
}
}
层次输出所有结点
public void levelOrder(TreeNode root) {
if (root == null)
return;
Queue<TreeNode> queue = new LinkedList<>();
queue.push(root);
while(!queue.isEmpty()) {
TreeNode node = queue.pop();
System.out.println(node.data);
TreeNode p = node.firstson;
while(p != null) {
queue.push(p);
p = p.nextbrother;
}
}
}
3.输出树的边
先序输出树的边
public void preOrder(TreeNode root) {
if (root == null)
return;
TreeNode p = root.firstson;
while (p != null) {
System.out.println(root.data + "," + p.data);
preOrder(p);
p = p.nextbrother;
}
}
层次输出树的边
public void levelOrder(TreeNode root) {
if (root == null)
return;
TreeNode p = root.firstson;
while (p != null) {
System.out.println(root.data + p.data);
p = p.nextbrother;
}
levelOrder(root.firstson);
levelOrder(root.nextbrother);
}
先序输出对应二叉树的边
public void print(TreeNode root) {
if (root == null)
return;
if (root.firstson != null) {
System.out.println(root.data + root.firstson.data);
print(root.firstson);
}
if (root.nextbrother != null) {
System.out.println(root.data + root.nextbrother.data);
print(root.nextbrother);
}
}