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