Difference in performance when inverting a binary tree

Now I have two solutions. But I can’t understand why the first solution is faster than the second solution.

First decision

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;
    }
}

Second solution

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;
    }
}
+4
source share
1 answer

. , - :
root.left root.right, , root.left root.right.
root.left root.right, . , node. , .

+3

Source: https://habr.com/ru/post/1607693/


All Articles