树与森林-基础算法题

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.输出树的结点

A
B
C
D
E
F
G
H
I
J

输出所有结点及其层次

/**
 * 依次输出(A,1) (B,2) (E,3) (F,3) (C,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.输出树的边

先序输出树的边

/**
 * 依次输出
 * AB, BE, BF
 * AC, CG, CH
 * AD, DI, DJ
*/
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;
    }
}

层次输出树的边

/**
 * 依次输出 
 * AB, AC, AD 
 * BE, BF, CG, CH, DI, DJ
*/
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);
	}
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值