最近在做leetcode上的题目,有一道题是要求交换二叉树左右子树。我一开始没有在函数体中加入如下代码:
if(root == null) return null;
结果发现出现空指针异常。我觉得上面这段代码有点多余,但是OJ缺了它通过不了。麻烦各位大神帮忙解决一下小弟的困惑。下面贴上整个程序的代码:
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } 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; if(root.left != null) invertTree(root.left); if(root.right != null) invertTree(root.right); return root; } }
Will his use case directly pass in null?
invertTree(null);
You add code, the first code is
if(root.left == null && root.right == null)
If the passed parameter is null, then root.left. Because root is null, calling the left attribute will report an exception
If you block the exception, then .root.left==null is true.
I don’t I haven’t understood his code, but I guess the code should be like this.
No need to go to such trouble.
Would this idea be more concise and clear?