我用这个答案完成了this leetcode问题
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
// if both are null, assign merge tree to null
if (t1 == null && t2 == null) return null;
// if t1 or t2 is null, add 0
int sum = (t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val);
TreeNode tSum = new TreeNode(sum); // declare locally to prevent overwriting
tSum.right = mergeTrees(t1.right, t2.right);
tSum.left = mergeTrees(t1.left, t2.left);
return tSum;
}
当t1或t2等于null时抛出NullPointerException。但是当我查找正确的答案时,它只是略有不同。
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
// if both are null, assign merge tree to null
if (t1 == null && t2 == null) return null;
// if t1 or t2 is null, add 0
int sum = (t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val);
TreeNode tSum = new TreeNode(sum); // declare locally to prevent overwriting
// pass null if either == null to avoid nullpointerexception
tSum.right = mergeTrees(t1 == null ? null : t1.right, t2 == null ? null : t2.right);
tSum.left = mergeTrees(t1 == null ? null : t1.left, t2 == null ? null : t2.left);
return tSum;
}
在不传递左或右节点值的情况下,它传递null。
为什么java只在第一种情况下抛出一个nullpointer异常,当两个参数看起来都等于null时?
答案 0 :(得分:0)
您正在对空对象(t1或t2)调用.right方法。在null对象上调用方法将导致null异常。
标题不正确 - 您没有传递空节点,而是传递空节点的子节点。