我试图合并两个二叉树,如果我使用“return root”最后,系统告诉我“错误:找不到符号:变量根”。当我添加“return root”时它可以工作对每一个条件。我不明白为什么。此外,在我过去的经验中,似乎我不必在递归函数调用之后编写return语句。有人可以解释一下吗?谢谢!
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) {
return null;
}
else if (t1 == null) {
TreeNode root = new TreeNode(t2.val);
root.left = mergeTrees(null, t2.left);
root.right = mergeTrees(null, t2.right);
}
else if (t2 == null) {
TreeNode root = new TreeNode(t1.val);
root.left = mergeTrees(t1.left, null);
root.right = mergeTrees(t1.right, null);
}
else {
TreeNode root = new TreeNode(t1.val + t2.val);
root.left = mergeTrees(t1.left, t2.left);
root.right = mergeTrees(t1.right, t2.right);
}
return root;
}
答案 0 :(得分:0)
您的变量root在if,else if和else语句中声明,因此一旦到达if语句块之外的返回,它就会失去作用域。如果你想返回root,我建议你这样做。
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
TreeNode root; //Declare it here so it doesn't lose scope
if (t1 == null && t2 == null) {
return null;
}
else if (t1 == null) {
root = new TreeNode(t2.val);
root.left = mergeTrees(null, t2.left);
root.right = mergeTrees(null, t2.right);
}
else if (t2 == null) {
root = new TreeNode(t1.val);
root.left = mergeTrees(t1.left, null);
root.right = mergeTrees(t1.right, null);
}
else {
root = new TreeNode(t1.val + t2.val);
root.left = mergeTrees(t1.left, t2.left);
root.right = mergeTrees(t1.right, t2.right);
}
return root;
}
答案 1 :(得分:0)
除非您使用JavaScript编程并使用var
,否则大多数algol languages中的变量都具有块范围。因此:
{ // new block scope started
TreeNode root = new TreeNode(t2.val); // New variable TreeNode created
} // Everything created in this scope gets destroyed
root; // Would no compile as root is an unbound variable
如果要创建要返回的变量,则需要在返回的同一范围内创建它。因此:
{
TreeNode root = null;
// .. you logic goes here
return root;
} // root goes out of scope here
Trivia:我提到了JavaScript,使用var
语言,你的代码可以使用:
function mergeTrees(t1, t2) {
if (t1 === null && t2 === null) {
return null;
}
else if (t1 === null) {
var root = new TreeNode(t2.val);
root.left = mergeTrees(null, t2.left);
root.right = mergeTrees(null, t2.right);
} else if (t2 === null) {
var root = new TreeNode(t1.val);
root.left = mergeTrees(t1.left, null);
root.right = mergeTrees(t1.right, null);
} else {
var root = new TreeNode(t1.val + t2.val);
root.left = mergeTrees(t1.left, t2.left);
root.right = mergeTrees(t1.right, t2.right);
}
return root;
}
这样做的原因是var
将最近的函数与作用域相关联,而条件中的块不会引入新的作用域。 ES6已使用let
和const
修复此问题,但其工作方式与其他algol语言相同,并且使用它们的风格更好。