617. Merge Two Binary Trees

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if (t1 == NULL && t2 == NULL) return NULL; else if (t1 != NULL && t2 == NULL) return t1; else if (t1 == NULL && t2 != NULL) return t2; else{ TreeNode * root; root-> val = t1->val + t2->val; root->left = mergeTrees(t1->left, t2->left); root->right = mergeTrees(t1->right, t2->right); return root; } }

1 Response

Error: in line 16, you do not initialize TreeNode.

Note the constructor does not work on TreeNode pointer type, but only on TreeNode type.

Should use this line instead:

TreeNode * root = new TreeNode(0);

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.