我试图合并2棵二叉树,而不用担心结果树的平衡。这是我的解决办法,但行不通。为什么Treenode ans和head在从合并函数返回时设置为0。据我所知,由于TreeNode不是原始类型,所以在调用合并函数https://leetcode.com/problems/merge-two-binary-trees/之后,应该用结果树更新指向ans的head。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
TreeNode ans = new TreeNode();
TreeNode head = ans;
if(root1!=null && root2==null)
return root1;
else if (root1==null && root2!=null)
return root2;
else if (root1!=null &&root2!=null)
merge (root1, root2,ans) ;
return head;
}
void merge (TreeNode root1, TreeNode root2,TreeNode ans)
{
if(root1!=null && root2==null)
root2 = new TreeNode(0);
else if (root1==null && root2!=null)
root1 = new TreeNode(0);
else if(root1==null &&root2==null)
return;
ans = new TreeNode(root1.val+root2.val);
merge(root1.left,root2.left,ans.left);
merge(root1.right,root2.right,ans.right);
}
}发布于 2022-05-06 17:52:53
问题是变量head和ans不会像您期望的那样被更新。Java是pass-by-value as explained here。这意味着ans是一个引用,您要将它的值传递给函数merge,然后在那里覆盖。
您还将使用ans的每个递归调用重新分配merge的值。要返回正确的值,您需要在第一次调用时返回分配给该变量的值。
希望这会有帮助。
发布于 2022-05-09 09:41:19
如果您更改将工作的对象的属性值的值,将通过值.传递引用。但是,如果将指针赋值给新对象,它将不会占用原始对象。
https://stackoverflow.com/questions/72142833
复制相似问题