反转二叉树时的性能差异

时间:2015-09-16 16:55:17

标签: java

现在我有两个解决方案。但我无法弄清楚为什么第一种解决方案比第二种解决方案更快。

第一个解决方案

public class Solution {
  public TreeNode invertTree(TreeNode root) {
        if(root == null)
            return root;

        if(root.left==null && root.right==null)
            return root;

        TreeNode temp = null;
        root.left = invertTree(root.left);
        root.right =invertTree(root.right);
        temp = root.left;
        root.left = root.right;
        root.right = temp;
        return root;
    }
}

第二个解决方案

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null)
            return null;

        if (root.left == null && root.right == null)
            return root;

        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}

1 个答案:

答案 0 :(得分:3)

值得看到实数。但是,如果我们谈论相当大的树,可能是因为缓存:
在第一个解决方案中,您读取root.left和root.right,然后执行反转,最后再次操作root.left和root.right。
在第二个解决方案中,您交换root.left和root.right,然后立即执行反转。因此,您可以避免每个节点至少有一次缓存未命中。实际上,即使指令代码可能只是一条指令,因为它可能会重用已经读过的变量。

相关问题