[英]Why is the time complexity of this function to check the balance of a Binary Tree O(n log n)?
Prompt from Cracking the Coding Interview by Gayle Laakmann McDowell: Gayle Laakmann McDowell 破解编码采访的提示:
Implement a function to check if a binary tree is balanced.实现 function 以检查二叉树是否平衡。 For this problem, a balanced tree is defined such that the heights of the two subtrees of any node do not differ by more than one.
对于这个问题,定义了一个平衡树,使得任何节点的两个子树的高度相差不超过一。
(Example implementation below.) (下面的示例实现。)
Question: Can you help me understand why the author states that isBalanced
has a time complexity of O(n log n)
?问题:你能帮我理解为什么作者说
isBalanced
的时间复杂度为O(n log n)
吗? I get it to some degree and can memorize this just fine, but I can't conceptualize why this is the case like I can for other time complexities like O(n^2)
.我在某种程度上得到了它并且可以很好地记住这一点,但是我无法概念化为什么会像其他时间复杂性(例如
O(n^2)
那样出现这种情况。
int getHeight(TreeNode root) {
if (root == null) { return -1; }
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
boolean isBalanced(TreeNode root) {
if (root == null) { return true; }
int heightDiff = getHeight(root.left) - getHeight(root.right);
if (Maths.abs(heightDiff) > 1) {
return false;
} else {
return isBalanced(root.left) && isBalanced(root.right);
}
}
// isBalanced([some node]) --> true/false
How do I visualize why isBalanced
is considered O(n log n)
?我如何想象为什么
isBalanced
被认为是O(n log n)
?
Lets say you have BST假设你有 BST
4 // No of nodes 1
/ \
2 6 // No of nodes 2
/ \ / \
1 3 5 7 // No of nodes 4
Your function isBalanced
is going through all nodes including the ones with no children and call getHeight
to calculate the height of left and right child.您的 function
isBalanced
正在遍历所有节点,包括没有孩子的节点,并调用getHeight
来计算左右孩子的高度。
The recursive relation of the function would be function 的递归关系为
which is derived from Master Theorem它源自主定理
a
= number of sub-problems in recursion a
= 递归子问题的数量
n/b
= size of each sub-problem n/b
= 每个子问题的大小
f(n)
= cost of work that has to be done outside the recursive calls f(n)
= 必须在递归调用之外完成的工作成本
a
is 2
because we have to visit both children nodes of each parent a
是2
因为我们必须访问每个父节点的两个子节点
b
is 2
because if you notice the number of nodes reduce by half each time you go a level above (from bottom). b
是2
,因为如果您注意到每次 go 上一级(从底部开始)时节点数减少一半。
f(n)
is n
because we have to call getHeight()
on each node f(n)
是n
因为我们必须在每个节点上调用getHeight()
Which satisfies the second case of Master Theorem that is满足 Master Theorem 的第二种情况,即
Putting the values to prove f(n) = O(n^logb(a))
将值用于证明
f(n) = O(n^logb(a))
Thus we get the time complexity of O(n log n)
因此我们得到
O(n log n)
的时间复杂度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.