现在我有两个解决方案。但是我不明白为什么第一个方案比第二个方案更快。
第一个方案:
第二种解决方案
第一个方案:
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;
}
}