Algorithm 求递推关系时间复杂度的主定理
我试图理解并实现主定理,以发现递推关系的时间复杂性 但是,我无法理解如何使用它来计算算法的时间复杂度 考虑这个算法来寻找二叉树的直径Algorithm 求递推关系时间复杂度的主定理,algorithm,recursion,time-complexity,master-theorem,Algorithm,Recursion,Time Complexity,Master Theorem,我试图理解并实现主定理,以发现递推关系的时间复杂性 但是,我无法理解如何使用它来计算算法的时间复杂度 考虑这个算法来寻找二叉树的直径 class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } /* Class to print the Diameter
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
/* Class to print the Diameter */
class BinaryTree
{
Node root;
/* Method to calculate the diameter and return it to main */
int diameter(Node root)
{
/* base case if tree is empty */
if (root == null)
return 0;
/* get the height of left and right sub trees */
int lheight = height(root.left);
int rheight = height(root.right);
/* get the diameter of left and right subtrees */
int ldiameter = diameter(root.left);
int rdiameter = diameter(root.right);
/* Return max of following three
1) Diameter of left subtree
2) Diameter of right subtree
3) Height of left subtree + height of right subtree + 1 */
return Math.max(lheight + rheight + 1,
Math.max(ldiameter, rdiameter));
}
/* A wrapper over diameter(Node root) */
int diameter()
{
return diameter(root);
}
/*The function Compute the "height" of a tree. Height is the
number f nodes along the longest path from the root node
down to the farthest leaf node.*/
static int height(Node node)
{
/* base case tree is empty */
if (node == null)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return (1 + Math.max(height(node.left), height(node.right)));
}
public static void main(String args[])
{
/* creating a binary tree and entering the nodes */
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("The diameter of the given binary tree is: "
+ tree.diameter());
}
}
我知道上述算法的时间复杂度是O(n^2)
只要看看它。因为每个节点在单个递归中调用的时间都很长
如何使用Master方法找到此算法的时间复杂度
我在寻找递归函数的时间复杂性方面完全是个新手。
我认为主定理是计算递归函数时间复杂度的一种方法
如何使用master方法或任何其他方法查找递归算法的时间复杂度
如果有人能教我如何找到递归函数的时间复杂度,那将是一个很大的帮助
谢谢 如果我们假设二叉树是平衡的,那么总时间复杂度是
T(n)
,并且T(n)=2T(n/2)+2T(n/2)+1
。第一个2T(n/2)
表示直径(左侧和右侧),第二个2T(n/2)
表示高度(左侧和右侧高度)。因此T(n)=4T(n/2)+1=O(n^2)
(的第一个案例)。你是如何得出这种关系的?我想学!以及4t(n/2)+1=O(n^2)的情况。很抱歉我可能听起来很蹩脚。但我真的很弱