【发布时间】:2019-03-05 22:49:01
【问题描述】:
我正在查看 Leetcode 上 problem 的第一个递归解决方案。这是建议的解决方案的代码。
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val)
&& isMirror(t1.right, t2.left)
&& isMirror(t1.left, t2.right);
}
我不明白的部分解决方案是为什么解决方案的作者说时间复杂度是 O(n)。假设我有输入:
1
/ \
2 2
这就是我在这种情况下跟踪调用堆栈的方式:
isMirror(1, 1)
(t1.val == t2.val) returns true
isMirror(2, 2) returns true
(t1.val == t2.val) returns true
isMirror(null, null) return true
isMirror(null, null) return true
isMirror(2, 2) returns true
(t1.val == t2.val) returns true
isMirror(null, null) return true
isMirror(null, null) return true
在上面的调用堆栈中,isMirror() 被调用了 7 次,而 n 为 3。对于 O(n) 的时间复杂度,isMirror() 应该只被调用了 3 次吗?还是我看错了?是不是调用栈只进了3层就说明时间复杂度是O(n)?
感谢您的帮助。
【问题讨论】:
标签: recursion time-complexity binary-tree