国科大-计算机算法设计与分析-卜东波作业1

问题一

Given a binary tree T, please give an O(n) algorithm to invert binary tree. For example belowinverting the left binary tree, we get the right binary tree.
算法思想:利用递归的方法,先将根节点的左右子树进行交换,然后再递归左子树和右子树,依次向下进行左右子树的交换,最后便可以实现树的翻转。

public class TreeNode {
    int val;
     TreeNode left;
     TreeNode right;
    TreeNode() {}
     TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }
TreeNode invertTree(TreeNode root) {
        if (root == null)
                return root;
            TreeNode t = root.left;
            root.left = root.right;
            root.right = t;
            t = invertTree(root.left);
            t = invertTree(root.right);
            return root;
    }

证明正确性:我们先从根节点进行左右子树的交换,这样可以实现第二层的翻转,然后再通过递归将第二层的左右子树进行交换,这样第三层的翻转也实现了,依此类推,当递归到叶子节点时便实现了整个树的翻转。
时间复杂度:O(n)
空间复杂度:O(h)(h是树的高度)

问题二

There are N rooms in a prison, one for each prisoner, and there are M religions, and each prisoner will follow one of them. If the prisoners in the adjacent room are of the same religion, escape may occur. Please give an O(n) algorithm to find out how many states escape can occur.
For example, there are 3 rooms and 2 kinds of religions, then 6 different states escape will occur.
算法思想:首先,我们要知道:会发生越狱的状态数=总状态数-不会发生越狱的状态数,所以我们分两部分来解决此问题:
总状态数:有n个房间,每个房间有m种可能的状态,所以总状态数为m^n
不会发生越狱的状态数:第1个房间可以有m种状态,其余房间只能有m-1种状态(除了上一个房间的那种状态),所以不会发生越狱的状态数为m*(m-1)^(n-1)

int pow(int a,int b){
	int res=1;
	while (b){
		if (b&1) res=res*a;
		a=a*a;
		b>>=1;
	}
	return res;
}
int nums(int m,int n)
{
	return pow(m,n)-m*pow(m-1,n-1);
}
	

时间复杂度:O(log₂N)
空间复杂度:O(1)

问题三

Given a binary tree, suppose that the distance between two adjacent nodes is 1, please give a solution to find the maximum distance of any two node in the binary tree.
算法思想:将大问题化为小问题。求每个节点的左子树深度和右子树深度,将他们求和便是此节点对应的最大距离。然后对所有节点的最大距离进行一个比较,最后取最大值。

int max=0;
    public int maxDistance(TreeNode root) {
       if (node == null) {
            return 0; 
        }
        int L = depth(node.left); 
        int R = depth(node.right); 
        max = Math.max(max, L+R); 
        return Math.max(L, R) + 1; 
    }

在这里插入图片描述
证明正确性:任意一条路径均可以被看作由某个节点为起点,从其左儿子和右儿子向下遍历的路径拼接得到。如图我们可以知道路径 [9, 4, 2, 5, 7, 8] 可以被看作以 2为起点,从其左儿子向下遍历的路径 [2, 4, 9] 和从其右儿子向下遍历的路径 [2, 5, 7, 8] 拼接得到。
假设我们知道对于该节点的左儿子向下遍历经过最多的节点数 L (即以左儿子为根的子树的深度) 和其右儿子向下遍历经过最多的节点数 R(即以右儿子为根的子树的深度),那么以该节点为起点的路径经过节点数的最大值即为 L+R 。
时间复杂度:O(n)
空间复杂度:O(h)(h是树的高度)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值