Merge two binary trees
Given two
binary trees, return amerged tree
Merge rules:
- return
sumif both nodes are exist - if a right node is
nullreturn left node - if a left node is
nullreturn right node
Example

/* Definition for TreeNode
public class TreeNode
{
public int Value;
public TreeNode Left;
public TreeNode Right;
public TreeNode(int value)
{
Value = value;
}
}
*/
public sealed class Solution
{
public TreeNode Merge(TreeNode one, TreeNode two)
{
}
}
Approach:
The easiest way is to use recursion and convert merge rules into a code. Could be following cases:
- Node
oneand nodetwoarenull - Only node
oneisnull - Only node
twoisnull - Node
oneand nodetwoare NOTnull
and we have to do the same merging for left and right subtree
Code:
public TreeNode Merge(TreeNode one, TreeNode two)
{
if (one == null && two == null)
{
return null;
}
if (one == null)
{
return two;
}
if (two == null)
{
return one;
}
one.Value += two.Value;
one.Left = Merge(one.Left, two.Left);
one.Right = Merge(one.Right, two.Right);
return one;
}
Recent articles
Nice to read